FileWriter没有创建新文件

img


没有创建成功b.txt文件,求个大佬解答

  1. 如果在本地测试,把源文件和目标文件指定到特定盘符试试。代码是没有问题。
  2. 可以进入到工程中,搜索下生成的文件是否存在。
public class FileTest6 {
    public static void main(String[] args) throws IOException {
        String pathName = "E:\\笔记\\test2.txt";
        File file = new File(pathName);
        FileWriter fr = null;
        try {
            file.createNewFile();
            System.out.println("写入之前文件的长度为:"+file.length()+"字节");
            fr = new FileWriter(pathName,true);  // 加true的意思是在原文件内容基础上进行追加
            String str = "今天是个好日子";
            fr.write(str);
            fr.flush();  // 清空缓存区
            System.out.println("写入之后文件的长度为:"+file.length()+"字节");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            fr.close();
        }
    }
}
结果
写入之前文件的长度为:0字节
写入之后文件的长度为:21字节

可以使用File类创建一个文件,更保险。

我用#CSDN#这个app发现了有技术含量的博客,小伙伴们求同去《IO流详细笔记。FileInputStream,FileReader,BufferedReader,FileOutputStream,FileWriter,BufferedWriter,序列化和反序列》, 一起来围观吧 https://blog.csdn.net/weixin_45842494/article/details/122290805?utm_source=app&app_version=5.0.0

这里有详细的关于流的操作,希望对你有所帮助。