输入文本到file.txt的,无需更换时,在环

问题描述:

我使用的缓冲笔者尝试输入文本到记事本,这是我来什么码了文本,输入文本到file.txt的,无需更换时,在环

import java.util.Scanner; 
import java.io.*; 
public class FileSample { 
    public static void main (String[] args) { 
    Scanner sc = new Scanner(System.in); 
    String yourtext = " "; 
    String fn = "file.txt"; 
    String choice = " "; 
    do{ 
    try{ 
     FileWriter fw = new FileWriter(fn); 
     BufferedWriter bw = new BufferedWriter(fw); 
     System.out.print("Enter text: "); 
     yourtext = sc.nextLine(); 
     bw.write(yourtext); 
     bw.newLine(); 

     bw.close(); 
     System.out.println("==================================="); 
     System.out.print("Do you still want to continue?:\n [Y]Yes \n [N]No 
     \n::"); 
     choice = sc.nextLine(); 
    }catch(IOException ex){ 
     System.out.println("Error writing to file '" + fn + "'"); 
    } 
    }while(choice.equalsIgnoreCase("Y")); 


} 
} 

所以问题是当用户想要继续并再次输入文本并完成该过程时,应该在file.txt中的文本被新输入的文本替换。

+0

因为您不应该创建一个新的Writer来覆盖用户输入的每一行文件。您可以将写入器配置为附加文件。但即便如此,您也应该保持作家和媒体流畅通,直到用户选择不继续。 –

只需添加FileWriter(fn,true)这将保留现有内容并将新内容附加到文件末尾。

+1

嘿,谢谢......它现在正在工作 – Pon

你的问题是,你只是在覆盖模式下打开fileWriter,以使其只需将新文本附加到现有文件,只需将new FileWriter(fn)替换为FileWriter(fn,true)即可解决该问题。

但是,我也注意到,你的排序处理不当的资源(在我看来),所以我建议你一旦打开流/读/写,并在年底关闭它们:

public static void main(String[] args) { 
    String yourtext = " "; 
    String fn = "file.txt"; 
    String choice = " "; 
    try (Scanner sc = new Scanner(System.in); 
      FileWriter fw = new FileWriter(fn);   // making sure to free resources after using them 
      BufferedWriter bw = new BufferedWriter(fw);) { 
     do { 
      System.out.print("Enter text: "); 
      yourtext = sc.nextLine(); 
      bw.write(yourtext); 
      bw.newLine(); 
      System.out.println("==================================="); 
      System.out.print("Do you still want to continue?:\n [Y]Yes \n [N]No \n::"); 
      choice = sc.nextLine(); 
     } while (choice.equalsIgnoreCase("Y")); 
    } catch (IOException ex) { 
     System.out.println("Error writing to file '" + fn + "'"); 
    } 
} 
+0

值得一提的是,让扫描仪在资源尝试中意味着System.in也将在块的结尾处关闭。这是可以的,因为块的结尾位于main()的末尾。但是如果你想在块之后进行任何进一步的输入,你将不得不将扫描仪带出资源试用版。 –