JAVA - 从文件中读取并写入另一个文件

时间:2016-03-26 17:21:15

标签: java file io

这是我的代码,我无法使其正常工作,它只从第一个文本文件中获得了总共3行的最后一行,并且仅将其大写,我无法弄清楚为什么

    import java.util.Scanner;
    import java.io.*;


    public class AllCapitals {
    public static void main(String[] args) {
        String readLine;

        String inFilePath = "/home/file.txt"; 
        String outFilePath = "/home/newFile.txt";


        try (BufferedReader bufferedReader = new BufferedReader(new FileReader(inFilePath))) {

        while ((readLine = bufferedReader.readLine()) != null) {
            readLine.toUpperCase();
            String upperC = readLine.toUpperCase();

            System.out.println(upperC);

            try (Writer writer = new BufferedWriter(new OutputStreamWriter(
                    new FileOutputStream(outFilePath), "utf-8"))) {
                    writer.write(upperC);
                }
            }
        } catch (IOException e) {
            System.out.println("Error.");
            e.printStackTrace();
        }
    }
}

编辑:忘了说功能。

我需要从普通文本文件中读取3行

    Hello.
    How are you ?
    Good, thank you !

输出应该在所有CAPS中,但我只得到最后一行“谢谢你”

1 个答案:

答案 0 :(得分:2)

那是因为你在从第一次读取行的同时重新创建输出文件。 在开始阅读之前创建一次输出文件,例如:

    try (BufferedReader bufferedReader = new BufferedReader(new FileReader(inFilePath));
         Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFilePath), "utf-8"))
    ) {
        while ((readLine = bufferedReader.readLine()) != null) {
            String upperC = readLine.toUpperCase();
            System.out.println(upperC);

            writer.write(upperC);
            writer.write(System.lineSeparator());
        }
    } catch (IOException e) {
        System.out.println("Error.");
        e.printStackTrace();
    }

其他一些改进:

  • 删除了无效的readLine.toUpperCase();
  • 为每一行添加换行符,否则所有大写的内容都在同一行