使用StringBuilder
代替String
然后
StringBuilder test=new StringBuilder();
然后在你的while循环中
test.append("your String");
或者您可以String
按如下方式使用
String test=new String();
test +=your_String;
尝试这个
Scanner sc=new Scanner(new FileReader("D:\\Test.txt"));
StringBuilder test=new StringBuilder();
String str;
while (sc.hasNext()){
str=sc.next();
System.out.println(str);
test.append(str);
}
读取特定行
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Read {
public static void main(String[] args) throws IOException {
FileReader fr=new FileReader("D:\\Test.txt");
BufferedReader br=new BufferedReader(fr);
StringBuilder test=new StringBuilder();
String str;
int count=1;
while ((str=br.readLine())!=null){
if(count==1){
System.out.println(str);
test.append(str);
}
count++;
}
}
}