读写文字。 在读写文本文件中,我必须打印文本文件中的所有数据,但它只打印最后一行如何获取所有行。 程序:
public class fs
{
try
{
BufferReader in = new BufferReader(FileReader(C:/Users/madhan kumar/Desktop/read.txt));
String s;
String[] result=null;
while((s=in.readLine())!=null)
{
result=s.split("\\|");
result = String[4];
String Name = result[0];
String age = result[1];
String Sex = result[2];
String field = result[3];
System.out.println("Name :"+Name+"Age :"+age+"Sex :"+Sex+"Field"+field);
BufferedWriter bw =new BufferedWriter (new FileWriter ("out.txt");
bw.write ("Name :"+Name+"Age :"+age+"Sex :"+Sex+"Field"+field);
Bw.close ();
}}
catch(Exception e)
{
System.out.println(e);
}
}
}
My txt file
malik|23|male|student
nakul|30|male|student
ram|27|male|worker
mak|25|male|student
答案 0 :(得分:1)
您的主要问题的答案是您只看到最后一行,因为每次写出.txt时都会创建一个新的BufferedWriter,当您这样做时,它会删除.txt文件中已有的文本。要解决此问题,只需在while循环之外声明BufferedWriter:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.util.StringTokenizer;
import java.io.FileReader;
import java.io.FileWriter;
public class fs{
public static void main(String[] args){
StringTokenizer str;
try
{
BufferedReader in = new BufferedReader(new FileReader("C:/Users/madhan kumar/Desktop/read.txt"));
BufferedWriter bw = new BufferedWriter (new FileWriter("out.txt"));
String s;
while((s=in.readLine())!=null){
str = new StringTokenizer(s, "|");
String name = str.nextToken();
String age = str.nextToken();
String sex = str.nextToken();
String field = str.nextToken();
System.out.println("Name: "+name+"\tAge: "+age+"\tSex: "+sex+"\tField: "+field);
bw.write("Name: "+name+"\tAge: "+age+"\tSex: "+sex+"\tField: "+field);
}
bw.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
我进行了一些小调整,最大的是我使用了StringTokenizer,它与你的分割方法完全相同,但是更有说服力。