【问题标题】:filewriter overwriting the file文件编写器覆盖文件
【发布时间】:2017-06-18 01:40:05
【问题描述】:

我正在尝试通过使用FileWriter("file.txt",true) 使文件写入器追加而不是覆盖,但它不起作用,还有另一个问题(不确定是否真实)是我不能使用File file1 = new File("a.txt") 创建文件所以我使用格式化程序。注意我是初学者,所以请尽可能详细说明我犯的错误。

public static void newPlayer(){
    String name = JOptionPane.showInputDialog("Write yourn name ","new player");
    System.out.println(name +" " +points);
    try {
        Formatter file1 = new Formatter(name+".txt");
        File file2 = new File(name+".txt");
        fw = new FileWriter(file2,true);
        String s = Integer.toString(points);
        fw.write(s);
        fw.close();
        file1.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }catch(Exception e){
        System.out.println(e);  
    }
}

【问题讨论】:

  • 你在file2中写入但关闭file1?
  • 你确定name + ".txt" 的结果是"file.txt"?为什么不能使用File file1 = new File("a.txt")?你遇到了什么问题?
  • if(!file1.exists()) file1.createNewFile() 如果不存在则创建一个新文件。
  • File file1 = new File("a.txt") 不会在磁盘上创建物理文件,它只是创建一个表示文件或目录名称的对象。

标签: java file overwrite filewriter


【解决方案1】:

删除关于file1的两行,反正它没有被使用。

使用格式化程序打开带有append=false 的文件,这会干扰 FileWriter 的设置(在后台使用相同的文件描述符?取决于操作系统?)。

...
try {
    File file2 = new File(name+".txt");
    FileWriter fw = new FileWriter(file2,true);
    String s = Integer.toString(points);
    fw.write(s);  
    // a line feed would make the file more readable
    fw.close();
} catch (...

【讨论】:

    【解决方案2】:

    我用格式化程序删除了 file1 行,虽然在我尝试之前它可以工作,但它没有创建文件。如果您有类似的问题并且未创建文件,请尝试 file.createnewfile();

    try {
        //Formatter file1 = new Formatter(name+".txt");
        File file2 = new File(name+".txt");
        // file2.createNewFile();
        fw = new FileWriter(file2,true);
        String s = Integer.toString(points);
        fw.write(s);
        fw.close();
        //file1.close();
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }catch(Exception e){
    System.out.println(e);  
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-03
      • 1970-01-01
      • 2012-04-19
      • 1970-01-01
      • 2023-03-28
      • 2011-05-08
      • 1970-01-01
      相关资源
      最近更新 更多