【问题标题】:FileWriter not working?文件编写器不工作?
【发布时间】:2018-04-25 05:28:44
【问题描述】:
import java.io.IOException;
import java.util.*;

public class Owner {
    public static Scanner sc = new Scanner(System.in);
    public static void main(String args[]) throws IOException {
        String n = sc.nextLine();
        Info.namec(n);
    }
}

这是第二个类,它应该在文本文件中打印“HELLO”。

import java.io.*;

public class Info {

    public static void namec(String n) throws IOException//name check
    {
        File f = new File("TEXT");
        FileWriter fw = new FileWriter(f);
        fw.write("HELLO!");
    }
}

此代码不起作用,文本文件中没有输入任何内容。 有 2 个类,“Hello”没有被打印出来。

【问题讨论】:

  • 添加fw.close();
  • Owner 类与问题有什么关系?
  • 旁注:你不需要一切都是静态的......
  • 正如@Elazar 所说,只需添加 fw.close()

标签: java file-io filewriter


【解决方案1】:

您没有关闭文件,而且看起来有一些缓冲正在进行,因此文件没有任何内容,因为它太短了。试试这个:

public static void namec(String n) throws IOException {
    File f = new File("TEXT");
    try (FileWriter fw = new FileWriter(f)) {
        fw.write("HELLO!");
    }
}

所谓的try-with-resources statement会自动关闭try()中打开的东西,这通常是可取的。

【讨论】:

  • 明白了!谢谢。
【解决方案2】:

单独调用 fw.write("String") 并不能保证数据将被写入文件。数据可能会简单地写入缓存,而不会写入磁盘上的实际文件。

我建议你使用以下方法,

  • fw.flush() - 当您希望刚刚写入的数据反映在实际文件中时调用此方法。
  • fw.close() - 当你写完所有需要通过调用 write 方法写入的数据时调用它。

【讨论】:

    【解决方案3】:

    每当您使用文件写入器时,它都会将数据存储在缓存中,因此您需要刷新和关闭文件写入器对象。

    我在这里添加示例代码,希望对您有所帮助。

    package com.testfilewriter;
    
    import java.io.FileWriter;
    
    public class FileWriterExample {
       public static void main(String args[]) {
        try {
            FileWriter fw = new FileWriter("D:\\testfile.txt");
            fw.write("Welcome to stack overflow.");
            fw.close();
        } catch (Exception e) {
            System.out.println(e);
        }
        System.out.println("File writing complete.");
       }
    }  
    

    【讨论】:

      猜你喜欢
      • 2012-08-06
      • 1970-01-01
      • 2019-01-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-23
      相关资源
      最近更新 更多