Filewriter 不会将文本附加到新创建的文件中

Ste*_*eve 2 java filewriter

我对 Java 还很陌生。我试图将“List:”添加到新文本文件的开头(如果它不存在)。相反,文本文件是空白的,输入内容位于一行空白下方。

File hi = new File("hi.txt");
try{
  if(!hi.exists()){
    System.out.printf("\nCreating 'hi.txt'."); 
    hi.createNewFile();
    String hello = "List:";
    new FileWriter(hi).append(hello);
  }
  else{
    System.out.printf("\nWriting to 'hi.txt'");
  }
  FileWriter writeHere = new FileWriter(hi, true);
  String uling = "hi";
  writeHere.append(uling);
  writeHere.close();
}
//error catching
catch(IOException e){
  System.out.printf("\nError. Check the file 'hi.txt'.");}
Run Code Online (Sandbox Code Playgroud)

iva*_*nyk 5

将 true 作为第二个参数传递给 FileWriter 以打开“追加”模式(在您创建的第一个 FileWriter 中)。

另外,您应该创建变量FileWriter,并在附加“List:”后关闭它,因为您离开该变量的范围。

因此,我将代码编辑如下:

File hi = new File("hi.txt");
try {
    if (!hi.exists()) {
        System.out.printf("\nCreating 'hi.txt'.");
        hi.createNewFile();
        String hello = "List:";
        FileWriter writer = new FileWriter(hi, true);
        writer.append(hello);
        writer.close();
    } else {
        System.out.printf("\nWriting to 'hi.txt'");
    }
    FileWriter writeHere = new FileWriter(hi, true);
    String uling = "hi";
    writeHere.append(uling);
    writeHere.close();
}
//error catching
catch (IOException e) {
    System.out.printf("\nError. Check the file 'hi.txt'.");
}
Run Code Online (Sandbox Code Playgroud)

注意:第 7-9 行的修改。

http://docs.oracle.com/javase/7/docs/api/java/io/FileWriter.html