BufferedReader从.txt文件读取段落并绘制为String

时间:2015-11-29 23:11:32

标签: java arraylist split bufferedreader

所以,我已经查看了大约11个类似于我正在寻找的问题,但不幸的是,这些解决方案并没有帮助我。我有一个文本文件,其中包含我正在制作的游戏的说明。这是一个段落,我想在文件中使用\n转到下一行。据我所知,这可以通过利用.split()来完成。我试过学习和使用它,但正如我所说,我还没有走远。 基本上我想使用BufferedReader读取我的文件,然后每次读取\n时,转到下一行并将所有这些字符串放在ArrayList 中。但是,通过调用ArrayList并使用drawString()更改for-loop以便打印最后一行下的行,是否可以 y value

2 个答案:

答案 0 :(得分:1)

阅读用途:

File file = new File("foo.txt");
BufferedReader br = new BufferedReader (new FileReader(file));
String line;

while((line = br.readLine()) != null){
 doSomething(line);
}

//EDIT: if you want to get all your lines to one String that seperates the lines with \n replace doSomething(line) with
String str = "";
while((line = br.readLine()) != null){
 str+=line.concat("\n");
}

写:

    File file = new File("foo.txt");
    String[] data = getMyData();// replace the method call with whatever you need
    final FileOutputStream fos = new FileOutputStream(file);
                final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(fos));
    for (final String s : data) {
                writer.write(s);
                writer.newLine();
    }

这两个代码段将协同工作。

EDIT2: 如果您有以下字符串

String str = "firstXsecondXthird";

然后

String strings[] = str.split("X");

会给你一个包含3个字符串的数组:

strings[0] first
strings[1] second
strings[2] third

答案 1 :(得分:0)

BufferedReader已经可以在新行上拆分输入:

BufferedReader b = new BufferedReader (new FileReader("foo.txt"));
String line;

while((line = b.readLine()) != null){
   //do stuff, line is current line
}