java - 将文件读取到字符串数组并显示每条记录

标签 java arrays file

我的代码应该读取文件并将每一行(每条记录)存储到一个字符串数组中。

我的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/

相关文章:

java - 使用 Java 的 Integer.toString() 以 26 为基数作为字母

java - Recyclerview 适配器的 notifyDataSetChanged 不更新 RecyclerView

java未知协议(protocol): e when downloading a file

java - 在 HBASE 中创建表时找不到类异常

java - Jetty http2 打开到同一目的地的多个连接

arrays - 如何编写内部数组长度不同的嵌套数组?

c - 访问字符串数组时出现奇怪的段错误

file - 如何在 Linux 中查找哪个进程正在泄漏文件句柄?

java - 从具有 OutputStream 的 Spring @Controller 返回文件

java - 添加长数字时 IndexOutOfBoundsException 错误