2

所以最近我在这里发布了关于 Java 的类似问题。每次有人回答我的问题时,就会出现更多问题。谢谢大家。解决了附加问题,现在使事情变得漂亮。

[文件.java]

public class File {

    public static void main(String[] args) {

        FileWrite fW = new FileWrite();

        try (BufferedReader br = new BufferedReader(new FileReader("B:\\LongIn.dat"))) {
            String stCurrent;
            while ((stCurrent = br.readLine()) != null) {
                System.out.println(stCurrent);
                fW.serializeAddress(stCurrent);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

[文件写入.java]

public class FileWrite {

    public void serializeAddress(String in) {
        try {
            File file = new File("B:\\LongOut.txt");
            if (!file.exists()) {
                file.createNewFile();
            }

            FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(in);

            bw.close();

            System.out.println("Done");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

现在我的程序在将字符串写入文件时追加。但是我有两个问题。

  1. 在阅读方面,将大量字符串存入某个变量以便我的程序可以使用它的好方法是什么?

  2. 附加输出有效,但组织得不好。如中,结果在输出文件中相互网格化。如何使输出全部排列并看起来不错?

4

2 回答 2

2

如果您希望将行分开,在不更改大部分代码的情况下最简单的方法是添加newLine()call afterwrite()像这样:

bw.write(in);
bw.newLine();
bw.close();

Javadoc:BufferedWriter#newLine()

于 2013-01-16T11:31:42.810 回答
1

apache Commons IO 怎么样,它们确实提供了许多有用的实用方法来简单地使用文件。查看类FileUtils了解更多信息。

于 2013-01-16T12:06:01.023 回答