【问题标题】:Writing order string into text file将订单字符串写入文本文件
【发布时间】:2014-03-06 06:37:44
【问题描述】:

这只是在文本文件中写入“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();

    }

【问题讨论】:

  • 有什么问题?你有什么例外吗?我试过你的代码,它对我有用(在一个新的主类中调用这两个函数之后)。可能您必须调用正确的函数nameOfFirstOrdernameOfSecondOrder?请提供完整的工作代码示例。
  • 真的很抱歉,你是对的,我调用了错误的方法。我的脑子疯了。对此感到抱歉。

标签: java file fileoutputstream bufferedwriter


【解决方案1】:

即使解决方案只是调用正确的方法,以下是对您的代码的一些改进:

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 并给它一个 append-boolean
  • 考虑使用FileWriter 而不是OutputStreamWriterFileOutputStream
  • 如果您使用的 Java 版本 >= 7,请使用 try-with-resource 语句。您可以轻松摆脱以良好方式关闭流的尝试。
  • BufferedWriter.flush() 也不需要,因为它将在关闭文件时完成(由 try-with-resource 语句完成)

【讨论】:

  • 感谢您的改进
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-28
  • 1970-01-01
  • 1970-01-01
  • 2011-10-24
相关资源
最近更新 更多