【问题标题】:How can I process an input to an output file line-by-line in Java?如何在 Java 中逐行处理对输出文件的输入?
【发布时间】:2021-05-31 05:14:34
【问题描述】:

我正在尝试从 .txt 文件中读取(逐行)以将表达式从前缀转换为后缀。我正在使用以下代码来读取和输出。如何将输入传递给 PrefixtoPosfix() 方法,对其进行处理,然后将结果输出到文本文件中。

示例: 如果前缀输入文件是(+ * AB / CD),它将使用我在程序PrefixtoPosfix()中为它设置的方法转换它并输出 AB * CD / + 在输出文件中。

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

    FileReader inputStream = null;
    FileWriter outputStream = null;

    try {
        inputStream = new FileReader("input.txt"); // input file
        outputStream = new FileWriter("output.txt"); // output file

        int c;
        while ((c = inputStream.read()) != -1) { // read and process one character
            if (c == 'a') // replace all occurrences of 'a' with '@'
                outputStream.write('@');
            else outputStream.write(c);
        }
    } finally {
        if (inputStream != null) inputStream.close();
        if (outputStream != null) outputStream.close();
    }
}

【问题讨论】:

    标签: java file input file-io output


    【解决方案1】:

    将您的 FileReader 包裹在 BufferedReader 中。它有一个readLine() 方法。

    【讨论】:

    • 写入文件怎么样?
    • 如果大多数Reader 对象都有关联的Writer,您认为您需要哪些对象?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-22
    • 1970-01-01
    • 1970-01-01
    • 2011-06-11
    • 1970-01-01
    • 2020-03-12
    • 1970-01-01
    相关资源
    最近更新 更多