BufferedReader 从 .txt 文件中读取段落并绘制为字符串
BufferedReader reading paragraph from .txt file and drawing as String
因此,我已经查看了大约 11 个与我正在寻找的问题类似的问题,但不幸的是,这些解决方案对我没有帮助。我有一个文本文件,其中包含我正在制作的游戏的说明。这是一个段落,我想在文件 中使用\n
转到下一行。据我了解,这可以通过利用 .split()
来完成。我曾尝试学习和使用它,但正如我所说,我还没有走得太远。 所以基本上我想使用 BufferedReader
读取我的文件,然后每次读取 \n
时,转到下一行并将所有这些字符串放入 ArrayList .但是,是否可以通过调用 ArrayList 并使用 for-loop
更改 y value
来 drawString()
以便打印下面的行最后一个?
A BufferedReader
已经可以在换行符上拆分输入:
BufferedReader b = new BufferedReader (new FileReader("foo.txt"));
String line;
while((line = b.readLine()) != null){
//do stuff, line is current line
}
阅读使用:
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();
}
这两个代码片段可以协同工作。
编辑2:
如果你有以下 String
String str = "firstXsecondXthird";
然后
String strings[] = str.split("X");
将为您提供一个包含 3 个字符串的数组:
strings[0] first
strings[1] second
strings[2] third
因此,我已经查看了大约 11 个与我正在寻找的问题类似的问题,但不幸的是,这些解决方案对我没有帮助。我有一个文本文件,其中包含我正在制作的游戏的说明。这是一个段落,我想在文件 中使用\n
转到下一行。据我了解,这可以通过利用 .split()
来完成。我曾尝试学习和使用它,但正如我所说,我还没有走得太远。 所以基本上我想使用 BufferedReader
读取我的文件,然后每次读取 \n
时,转到下一行并将所有这些字符串放入 ArrayList .但是,是否可以通过调用 ArrayList 并使用 for-loop
更改 y value
来 drawString()
以便打印下面的行最后一个?
A BufferedReader
已经可以在换行符上拆分输入:
BufferedReader b = new BufferedReader (new FileReader("foo.txt"));
String line;
while((line = b.readLine()) != null){
//do stuff, line is current line
}
阅读使用:
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();
}
这两个代码片段可以协同工作。
编辑2: 如果你有以下 String
String str = "firstXsecondXthird";
然后
String strings[] = str.split("X");
将为您提供一个包含 3 个字符串的数组:
strings[0] first
strings[1] second
strings[2] third