这是我的代码
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package namereader;
import java.util.*;
import java.io.*;
/**
*
* @author jpowell1225
*/
public class NameReader {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws IOException{
// TODO code application logic here
boolean onoff = true;
int count = 0;
int count2 = 0;
String first = null;
FileWriter fw = new FileWriter("txt",true);
String last = null;
Scanner scan = new Scanner(System.in);
scan.useDelimiter(" ");
//scan.useDelimiter();
while(onoff){
first = scan.nextLine();
if(first.equals("quit")){
break;
}
fw.write(first);
FileReader fr = new FileReader("txt");
Scanner src = new Scanner(fr);
count = first.lastIndexOf(" ");
count2 =first.indexOf(" ", 2);
System.out.println("Your name is: " + first.substring(count) + " " + first.substring(count2, count2+2) + ". " + first.substring(0, count2));
}
fw.close();
scan.close();
}
}
虽然它确实正确输出了输入的名称(从First Middle Last切换到Last First Middle Initial),但它确实正确地创建了一个名为“txt”的文件,每当我打开文件时它都是空的。
我需要能够在文件“txt”中添加多个输入。 TIA
答案 0 :(得分:0)
您忘记了flush()
输出流
fw.flush();//flush it before close it.
fw.close();
您也可以使用try(<<Closable>>){}
让Java自动关闭(FileWriter
)。
修改强>
try(<<closable_0>>;<<closable_1>>;...){}
是一个自java1.7以来的新方案,它用于让jvm在块之后自动关闭closable
对象。在你的代码中它可能是这样的。
try(Scanner scan = new Scanner(System.in);FileWriter fw = new FileWriter("txt",true);){
//using the objects
}//jre will closes both :scan and :fw objects automatically