这只是在文本文件中写“test 2”。 如何写第一行将是“test 1”,第二行将是文本文件中的“test 2”。
if(s1.equals("test 1")&&s2.equals("test 2")){
WriteNameOrderInFile.nameOfFirstOrderForImage(s1);
WriteNameOrderInFile.nameOfSecondOrderForImage(s2);
WriteNameOrderInFile类:
public class WriteNameOrderInFile(){
public static void nameOfFirstOrder(String s) throws IOException {
String nameFileDoctor="C:/append info.txt";
FileOutputStream fos = new FileOutputStream(nameFileDoctor);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
bw.write(s);
bw.newLine();
bw.flush();
bw.close();
}
public static void nameOfSecondOrder(String s) throws IOException {
File file= new File("C:/append info.txt");
FileOutputStream fos2= new FileOutputStream(file,true);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos2));
bw.write(s);
bw.newLine();
bw.flush();
bw.close();
}
答案 0 :(得分:2)
即使解决方案只是调用正确的方法,以下是对代码的一些改进:
public class WriteNameOrderInFile {
public static void writeToFile(String text, boolean append) {
File file = new File("C:/append info.txt");
try (BufferedWriter bw = new BufferedWriter(new FileWriter(file, append))) {
bw.write(text);
bw.newLine();
} catch (IOException e) {
// do some exception handling
System.err.println("Can't write to file!");
}
}
public static void main(String[] args) {
// just a sample call with the code you provided
String s1 = "test 1";
String s2 = "test 2";
if (s1.equals("test 1") && s2.equals("test 2")) {
writeToFile(s1, false); // boolean is false, so write (replace) text
writeToFile(s2, true); // append is true, so append text
}
}
}
对代码改进的一些解释:
writeToFile
并为其提供追加 -boolean OutputStreamWriter
和FileOutputStream
考虑使用FileWriter
BufferedWriter.flush()
也不需要,因为它将在关闭文件时完成(try-with-resource语句完成的操作)