如何在用户输入字符串后获取txt文件中的nextLine?

时间:2013-12-04 04:33:12

标签: java file-io

刚刚开始编码,发现自己不知所措,不同类型的写入文件。我正在使用File和PrintStream库。我的问题是,在用户完成键入注释并重新打开文件后,文件将被覆盖。我希望只添加一个nextLine函数,所以当再次打开文件时,我们只需要向line2添加文本。提前谢谢。

这是我的代码:

if(userOption.equals("open") || userOption.equals("OPEN") ){
        System.out.print("Please enter the name of the file you want to open : ");
        fileNameOpen = kybd.nextLine();
        File input = new File( fileNameOpen );
        PrintStream  print = new PrintStream( input );
        System.out.print("Now you can start typing your notes: ");
       // print.println(userNotes = kybd.nextLine());
        print.println(userNotes = kybd.nextLine());
        print.close();

    }//end of if

3 个答案:

答案 0 :(得分:0)

如果你只想要一些简单的东西,这将有效:

try {
    PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(fileNameOpen , true)));
    userNotes = kybd.nextLine()
    out.println(userNotes);
    out.close();
} catch (IOException e) {
    //oh noes!
}

FileWriter构造函数的第二个参数将告诉它附加到文件(而不是清除文件)。

当然,您需要将此合并到您的逻辑中。

答案 1 :(得分:0)

PrintWriter out = new PrintWriter(
                  new BufferedWriter(new FileWriter(fileNameOpen, true)));

FileWriter中的第二个参数将允许您附加一行

答案 2 :(得分:0)

  if(userOption.equals("open") || userOption.equals("OPEN") ){
    System.out.print("Please enter the name of the file you want to open : ");
    Scanner kybd = new Scanner(System.in);
    String fileNameOpen = kybd.next();
    kybd.nextLine();

    try{
         String data = " This content will append to the end of the file";

         File file = new File(fileNameOpen);

         // if file does not exist create it
         if(!file.exists()){
             file.createNewFile();
         }

         //true = append file
         FileWriter fWriter = new FileWriter(file.getName(),true);
         BufferedWriter writer = new BufferedWriter(fWriter);
         writer.write(data);
         writer.close();

    }catch(IOException e){
        System.out.println(e.getMessage());
    }
}//end of if