首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Java PrintWriter FileNotFound

Java PrintWriter FileNotFound
EN

Stack Overflow用户
提问于 2015-04-18 18:07:09
回答 3查看 9.2K关注 0票数 5

我在写txt文件时遇到了麻烦。我得到了一个FileNotFound异常,但我不知道为什么,因为文件肯定在那里。这是密码。

代码语言:javascript
复制
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.File;

public class Save
{
    public static void main(String[] args)
    {
        File file = new File("C:/Users/Daniel/Desktop/Programs/Save Data Test/save.txt");
        PrintWriter pw = new PrintWriter(file);
        pw.println("Hello World");
        pw.close();
    }
}
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2015-04-18 18:39:20

在创建PrintWriter put之前,必须创建包含其目录的实际文件

代码语言:javascript
复制
file.mkdirs();
file.createNewFile();

用这个和适当的尝试和捕捉块会看起来像这样.

代码语言:javascript
复制
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.File;

public class Save
{
    public static void main(String[] args)
    {
        File file = new File("save.txt");
        try {
            file.mkdirs();
            file.createNewFile();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        try {
            PrintWriter pw = new PrintWriter(file);
            pw.println("Hello World");
            pw.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

    }
}
票数 9
EN

Stack Overflow用户

发布于 2015-04-18 20:17:24

仅仅因为您知道文件在那里,并不意味着您的代码在尝试处理之前不应该检查它的存在。

至于您的FileNotFound异常,如果IDE检测到可能发生异常,一些Java会强迫您编写try/catch块。

例如,NetBeans代码甚至不会编译:

您必须编写一个try/catch块来处理潜在的异常

代码语言:javascript
复制
public static void main(String[] args) {
    File file = new File("C:/Users/Daniel/Desktop/Programs/Save Data Test/save.txt");
    if (file.exists()) {
        try {
            PrintWriter pw = new PrintWriter(file);
            pw.println("Hello World");
            pw.close();
        } catch (FileNotFoundException fnfe){
            System.out.println(fnfe);
        }
    }
}
票数 2
EN

Stack Overflow用户

发布于 2022-06-16 13:26:47

转这个:public static void main(String[] args)

这方面:

代码语言:javascript
复制
public static void main(String[] args) throws FileNotFoundException

一切都会好起来的。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29720934

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档