我使用下面的代码从txt文件中读取。
ArrayList<String> elements = new ArrayList<String>();
String line = null;
BufferedReader in = new BufferedReader(new FileReader("example.txt"));
//in.close();
while((line = in.readLine()) != null){
elements.add(line);
}
check1 = (elements.get( 0));
System.out.println("HEYAAA \n" + check1);
//GUIServer guiServer = new GUIServer();
}catch(Exception e){
System.out.println("Error while reading file line by line:" + e.getMessage());
}
我有&#34; 1。我的名字是bob \ n 2.帮助你\ n 3.只是测试&#34;在txt文件里面全部在一行..但是当我把它读到java中时,它会在一行中打印并且不会读取&#34; \ n&#34; ..我怎么能这样做才能打印出来在3行,所以它读取&#34; \ n&#34; ..?
或者我可以在新行上分别在txt文件上手动分隔它们,但是如何读取3行并存储到一个变量中??
哪种方式更容易,我会感激你的帮助。
答案 0 :(得分:0)
1)&#34; example.txt&#34;包含:"1. my name is bob \n 2. help you \n 3. Just testing"
2)你想把它解释为
1. my name is bob
2. help you
3. Just testing
3)缓冲的读者无法转换&#34; \ n&#34;自动 - 你必须在你的程序中这样做。
4)建议:
String.split()或String.replace()。
ADDENDUM - 这是一个完整的例子:
1)代码:
package com.so.readlines;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Collections;
public class ReadLines {
public static void main(String[] args) {
// Declare our array list
ArrayList<String> elements = new ArrayList<String>();
String line;
BufferedReader in = null;
try {
// Open file
in = new BufferedReader(new FileReader("example.txt"));
// Read next line (with embedded "\n" text string)
while((line = in.readLine()) != null){
// ... split "line" into String[] array; add it to "elements" arraylist
// Collections.addAll(elements, line.split("\\\\n"));
String[] a = line.split("\\\\n");
Collections.addAll(elements, a);
}
in.close();
//String check1 = (elements.get( 0));
//System.out.println("HEYAAA \n" + check1);
//GUIServer guiServer = new GUIServer();
}
catch(Exception e){
System.out.println("Error while reading file line by line:" + e.getMessage());
}
// Print contents of array list
int i = 0;
for (String s : elements) {
System.out.println ("elements[" + i++ + "]=" + s);
}
}
}
2)Example.txt(注意&#34之后的额外空格; \ n&#34;):
1. my name is bob \n 2. help you \n 3. Just testing
3)示例输出:
elements[0]=1. my name is bob
elements[1]= 2. help you
elements[2]= 3. Just testing
&#39;希望有所帮助...