我创建了一个名为'test.txt'的文件,然后从用户那里接受输入以将输入写入文件。一切运行良好。该程序根本不显示任何错误。文件被创建并且程序从用户处获得输入,但是当我检查文件的内容时,它是空的。任何人都可以找出我的代码有什么问题吗?代码如下。创建文件并写入文件
package InputOutput;
import java.io.*;
public class CharacterFileReaderAndFileWriter{
private BufferedReader br = null;
private BufferedWriter bw = null;
private PrintWriter pw = new PrintWriter(System.out, true);
public File createFile() throws IOException{
File f = new File("test.txt");
return f;
}
public void writeToFile() throws IOException{
try{
bw = new BufferedWriter(new FileWriter(createFile()));
}
catch(FileNotFoundException ex){
ex.printStackTrace();
}
//take input from the console (user)
br = new BufferedReader(new InputStreamReader(System.in));
String s;
pw.println("Please enter something");
pw.println("To stop the program, enter 'stop'");
do{
s = br.readLine();
if(s.compareTo("stop")==0)
break;
s+= "\r\n";//adding an new line to the string s
bw.write(s);
}
while(s.compareTo("stop")!=0);
br.close();
bw.close();
}
public static void main(String[] args) throws IOException{
CharacterFileReaderAndFileWriter cfr = new CharacterFileReaderAndFileWriter();
cfr.writeToFile();
}
}
我试过你的代码。它没有任何改变对我来说工作得很好。输出文件包含我输入的文本。你没有在特定条件下获取文件内容吗? – krishnakumarp 2012-04-22 02:01:03
现在正在工作。该文件不是与源代码文件位于同一文件夹中的,因此我指定了完整路径。感谢你的时间人。真的很感激它。 :) – 2012-04-22 02:02:39
@krishnakumarp是的,IDE并没有真正为我在目录中创建文件,只有文件名。所以我在创建文件时输入了完整路径。它现在工作正常 – 2012-04-22 02:03:52