use*_*913 5 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();
    }
}
在创建PrintWriterput 之前,必须使用其目录创建实际文件
file.mkdirs();
file.createNewFile();
使用正确的try和catch块看起来像这样......
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();
        }
    }
}
| 归档时间: | 
 | 
| 查看次数: | 5811 次 | 
| 最近记录: |