Java PrintWriter 文件未找到

标签 java file printwriter

我在写入 txt 文件时遇到问题。我收到 FileNotFound 异常,但我不知道为什么,因为该文件肯定存在。这是代码。

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();
    }
}

最佳答案

在创建 PrintWriter 之前,您必须创建带有目录的实际文件

file.mkdirs();
file.createNewFile();

将它与适当的 try 和 catch block 一起使用看起来像这样......

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();
        }

    }
}

关于Java PrintWriter 文件未找到,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29720934/

相关文章:

Java RegEx 反斜杠数字

java - 如何用Java编写文件列表

java - PrintWriter:读取和写入同一文件 - 文件在再次打开之前似乎未保存

java - 打印编写器格式

java - 使用 Spring Security 动态配置 LDAP 服务器

java - 如何从 JTextPane 中删除图片?

c# - File.WriteAllText 真的会抛出 FileNotFoundException 吗?

java - 我无法将此代码排列在标题下方

java - Activity 未找到异常 : No Activity found to handle Intent { (has extras) }

python - 避免缓冲读取 "for line in ..."