我的代码应该读取文件并将每一行(每条记录)存储到一个字符串数组中。
我的txt文件是:
FName Lname Number
second secondsecond 22
thired thithird 33
fourth fourfourr 44
fifth fiffif 55
但是,当我运行代码时,我的程序不显示每行的第一个字符! 显示如下:
econd secondsecond 22
hired thithird 33
ourth fourfourr 44
ifth fiffif 55
我的代码:
public class ReadfileIntoArray {
String[] columns=new String[] {"FName","Lname","Number"};
String[] data=new String[100];
public void read() throws IOException{
FileReader fr=new FileReader("D:\\AllUserRecords.txt");
BufferedReader br=new BufferedReader(fr);
String line;
while((line=br.readLine())!=null){
for(int i=0;i<=br.read();i++){
data[i]=br.readLine();
System.out.println(data[i]);
}
}
br.close();
System.out.println("Data length: "+data.length);
}
public static void main(String[] args) throws IOException{
ReadfileIntoArray rfta=new ReadfileIntoArray();
rfta.read();
}
}
我想查看数据长度:5(因为我有五行),但我看到100!
(我想要抽象表模型的这些信息)
谢谢。
最佳答案
因为您在第二行将数组大小声明为 100。所以你基本上有两个选择,如果文件中的行数不会改变,那么将数组的大小声明为 5。如果它会变化,那么我建议你使用例如 ArrayList .
List<String> data = new ArrayList<String>();
//in the while loop
data.add(br.readLine());
关于java - 将文件读取到字符串数组并显示每条记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14175449/