尝试使用FileWriter写入输出文件

时间:2016-11-05 10:28:18

标签: java while-loop switch-statement inputstream bufferedreader

我正在尝试将我的代码输出保存到文本文件中,当我在不同的项目上运行它时,它会生成输出文件并分别存储输出,但是当我在不同的项目中运行相同的代码时它给了我空白的输出文件,我真的不知道是什么问题。我很困惑在哪里放置.close()函数和flush函数。提前谢谢!

    FileWriter output = new FileWriter("set.txt");
    BufferedWriter writer = new BufferedWriter(output);
    InputStream fis_n = new     FileInputStream("/Users/User/NetBeansProjects/Test/src/test/sample.txt");
    InputStreamReader isr_n = new InputStreamReader(fis_n, Charset.forName("UTF-8"));
    BufferedReader br_n = new BufferedReader(isr_n);

 while ((input = br_n.readLine()) != null) {
        String[] s = input.split(":");
        if (s[1].equals(text)) {
            writer.write(s[0] + "'s result is " + sample_text);
            writer.newLine();
            break;
        }
 }
  writer.close();
  output.close();

这是编辑后的代码的样子,但运行程序时输出文件“set.txt”仍为空。

    FileWriter output = new FileWriter("set.txt");
    BufferedWriter writer = new BufferedWriter(output);
    InputStream fis_n = new     FileInputStream("/Users/User/NetBeansProjects/Test/src/test/sample.txt");
    InputStreamReader isr_n = new InputStreamReader(fis_n, Charset.forName("UTF-8"));
    BufferedReader br_n = new BufferedReader(isr_n);

  try {
        while ((input = br_n.readLine()) != null) {

            String[] s = input.split(":");
        if (s[1].equals(text)) {
            writer.write(s[0] + "'s result is " + sample_text);
            writer.newLine();
            break;
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            writer.close();
            fis_n.close();
            isr_n.close();
            br_n.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    // fis_n.close();
    //isr_n.close();
    //br_n.close();
}

这是最终代码的样子:

     public static void dictionary(String sample_text, String text) throws FileNotFoundException, IOException {

 try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                new      FileInputStream("/Users/User/NetBeansProjects/Test/src/test/sample.txt"),
                Charset.forName("UTF-8")
        ));
             try {
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
                    new FileOutputStream("/Users/User/NetBeansProjects/Test/src/test/set.txt"),
                    Charset.forName("UTF-8")
            ));
            try {
                String input;
                while ((input = reader.readLine()) != null) {
                    String[] s = input.split(":");
                    if (s[1].equals(text)) {
                        writer.write(s[0] + "'s result is " + sample_text);
                        writer.newLine();
                        break;
                    }
                }
            } finally {
                writer.close();
            }
        } finally {
            reader.close();
        }
    } catch (IOException e) {
        // Error handling
    }
  }

这是调用字典方法的主要方法。

   public static void main(String[] args) throws FileNotFoundException, IOException {

 case 2: {
                BufferedReader d_br = new BufferedReader(new InputStreamReader(
                        new FileInputStream("/Users/User/NetBeansProjects/Test/src/test/input_file.txt"),
                        Charset.forName("UTF-8")
                ));

                try {

                    String d_line;
                    while ((d_line = d_br.readLine()) != null) {

                    String h_input = test(d_line);
                    dictionary(d_line, h_input);

                    }
                } catch(IOException e){

                }finally {
                    d_br.close();
                }
                break;
            }
  }

1 个答案:

答案 0 :(得分:3)

您应该在writer.close()循环之后while放入finally部分。

如果不需要存储部分处理的文件(在大多数情况下),则可以删除flush。在另一种情况下,最好将它留在原处。

Java 7+上资源使用的一般情况如下所示(此语法称为try-with-resources

try (
    Resource resource1 = // Resource 1 initialization
    Resource resource2 = // Resource 2 initialization
    ...
) {
    // Resource utilization
} catch (XXXException e) {
    // Something went wrong
}

通过try-with-resources自动释放(关闭)资源。

如果你需要使用Java 6或更早版本,上面的代码可以粗略地翻译成以下代码(实际上有一些细微的差别,这在这个级别的细节上并不重要)。

try {
    Resource1 resource1 = // Resource initialization
    try {
        Resource2 resource2 = // Resource initialization
        try {
            // Resource utilization
        } finally {
            // Free resource2
            resource2.close();
        }
    } finally {
        // Free resource1
        resource1.close();
    }
} catch (XXXException e) {
    // Something went wrong
}

注意,嵌套的try-finally块如何用于资源管理。

在您的特定情况下,我们需要管理两个资源:ReaderWriter,因此代码如下所示:

try (
        // Notice, we build BufferedReader for the file in a single expression
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                new FileInputStream("sample.txt"),
                StandardCharsets.UTF_8 // Better replacement for Charset.forName("UTF-8")
        ));
        // Alternative way to do the same
        // BufferedReader reader = Files.newBufferedReader(Paths.get("sample.txt"), StandardCharsets.UTF_8);

        // Output charset for writer provided explicitly
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
                new FileOutputStream("set.txt"),
                StandardCharsets.UTF_8
        ))
        // Alternative way to do the same
        // BufferedWriter writer = Files.newBufferedWriter(Paths.get("set.txt"), StandardCharsets.UTF_8)
) {
    String input;
    while ((input = reader.readLine()) != null) {
        String[] s = input.split(":");
        if (s[1].equals(text)) {
            writer.write(s[0] + "'s result is " + text);
            writer.newLine();
            break;
        }
    }
} catch (IOException e) {
    // Error handling
}

或者,使用pre-Java7语法:

try {
    BufferedReader reader = new BufferedReader(new InputStreamReader(
            new FileInputStream("sample.txt"),
            Charset.forName("UTF-8")
    ));
    try {
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
                new FileOutputStream("set.txt"),
                Charset.forName("UTF-8")
        ));
        try {
            String input;
            while ((input = reader.readLine()) != null) {
                String[] s = input.split(":");
                if (s[1].equals(text)) {
                    writer.write(s[0] + "'s result is " + text);
                    writer.newLine();
                    break;
                }
            }
        } finally {
            writer.close();
        }
    } finally {
        reader.close();
    }
} catch (IOException e) {
    // Error handling
}