如何在输出文件中逐行写入而不替换旧行

时间:2016-06-24 10:22:47

标签: java

我有一个包含以下行的文件

ar1 = [[Hello how are you], [I am doing fine] , [How about you] , [What do you do]]
ar2 = [[hey], [how are you] , [whats up] , [nothing much]]

List<List<String>> ar1 = new ArrayList<List<String>>();
List<List<String>> ar2 = new ArrayList<List<String>>();

for (int i = 0; i < ar1.size(); i++) {
                for (int j = 0; j < ar2.size(); j++) {
                     if(ar1.get(i).get(0).equalsIgnoreCase(ar2.get(j).get(0)) ){
                         PrintStream out = new PrintStream(new FileOutputStream("C:/output.txt"));
                         out.println(ar1.get(i));
                         out.println(ar2.get(j))
                         out.flush();
                     }
                }
            }

此文件的输出仅打印“你做什么”和“没什么”。如何打印输出文件中的所有行。

The output should be 
Hello how are you 
hey 
I am doing fine  
how are you and so on

2 个答案:

答案 0 :(得分:3)

只需将您的PrintStream声明移到循环之外。

确实new FileOutputStream(File)将从文件的开头开始写入,因为在这种情况下禁用了追加模式,以便您覆盖文件的先前内容。如果您希望始终在文件末尾附加新内容,则可能对其他构造函数new FileOutputStream(File, boolean)感兴趣。

我相信你想要达到的目标更像是:

List<List<String>> ar1 = Arrays.asList(
    Arrays.asList("Hello how are you"),
    Arrays.asList("I am doing fine"),
    Arrays.asList("How about you"),
    Arrays.asList("What do you do")
);
List<List<String>> ar2 = Arrays.asList(
    Arrays.asList("hey"),
    Arrays.asList("how are you"),
    Arrays.asList("whats up"),
    Arrays.asList("nothing much")
);
try (PrintStream out = new PrintStream(new FileOutputStream("C:/output.txt"))) {
    for (int i = 0; i < ar1.size() || i < ar2.size(); i++) {
        if (i < ar1.size() && !ar1.get(i).isEmpty()) {
            out.println(ar1.get(i).get(0));
        }
        if (i < ar2.size() && !ar2.get(i).isEmpty()) {
            out.println(ar2.get(i).get(0));
        }
        out.flush();
    }            
}

<强>输出:

Hello how are you
hey
I am doing fine
how are you
How about you
whats up
What do you do
nothing much

注意:您应该List String而不是List List String

答案 1 :(得分:0)

我认为你的代码应该是这样的

ar1 = [[Hello how are you], [I am doing fine] , [How about you] , [What do you do]]
ar2 = [[hey], [how are you] , [whats up] , [nothing much]]

List<List<String>> ar1 = new ArrayList<List<String>>();
List<List<String>> ar2 = new ArrayList<List<String>>();
String strOutput = "";
String newline = System.getProperty("line.separator");

for (int i = 0; i < ar1.size(); i++) {
     for (int j = 0; j < ar2.size(); j++) {
          if(ar1.get(i).get(0).equalsIgnoreCase(ar2.get(j).get(0)) ){
                 if (i > 0 || j > 0) {
                      strOutput += newline;
                 }
                 strOutput += ar1.get(i);
                 strOutput += newline;
                 strOutput += ar2.get(j);
           }
     }
}

PrintStream out = new PrintStream(new FileOutputStream("C:/output.txt"));
out.println(strOutput);
out.flush();