Java 将文本文件读入数组

Java 将文本文件读入数组,java,Java,我想把一个文本文件读入数组。我该怎么做 data=新字符串[lines.size] 我不想在数组中硬编码10 BufferedReader bufferedReader = new BufferedReader(new FileReader(myfile)); String []data; data = new String[10]; // <= how can I do that? data = new String[lines.size] for (int i=0; i<lin

我想把一个文本文件读入数组。我该怎么做

data=新字符串[lines.size]

我不想在数组中硬编码10

BufferedReader bufferedReader = new BufferedReader(new FileReader(myfile));
String []data;
data = new String[10]; // <= how can I do that? data = new String[lines.size]

for (int i=0; i<lines.size(); i++) {
    data[i] = abc.readLine();
    System.out.println(data[i]);
}
abc.close();
BufferedReader BufferedReader=new BufferedReader(new FileReader(myfile));
字符串[]数据;

数据=新字符串[10];// 使用ArrayList或其他动态数据结构:

BufferedReader abc = new BufferedReader(new FileReader(myfile));
List<String> lines = new ArrayList<String>();

while((String line = abc.readLine()) != null) {
    lines.add(line);
    System.out.println(data);
}
abc.close();

// If you want to convert to a String[]
String[] data = lines.toArray(new String[]{});
BufferedReader abc=newbufferedreader(newfilereader(myfile));
列表行=新的ArrayList();
而((字符串行=abc.readLine())!=null){
行。添加(行);
系统输出打印项次(数据);
}
abc.close();
//如果要转换为字符串[]
String[]data=lines.toArray(新字符串[]{});

使用
列表
。最后,如果需要,可以将其转换回
字符串[]

BufferedReader abc = new BufferedReader(new FileReader(myfile));
List<String> data = new ArrayList<String>();
String s;
while((s=abc.readLine())!=null) {
    data.add(s);
    System.out.println(s);
}
abc.close();
BufferedReader abc=newbufferedreader(newfilereader(myfile));
列表数据=新的ArrayList();
字符串s;
而((s=abc.readLine())!=null){
数据。添加;
系统输出打印项次;
}
abc.close();

如果不允许您使用dtechs方式执行此操作,并使用ArrayList,请将其读取两次:第一次读取用于声明数组的行数,第二次读取用于填充数组

您可以这样做:

  BufferedReader reader = new BufferedReader(new FileReader("file.text"));
    int Counter = 1;
    String line;
    while ((line = reader.readLine()) != null) {
        //read the line 
        Scanner scanner = new Scanner(line);
       //now split line using char you want and save it to array
        for (String token : line.split("@")) {
            //add element to array here 
            System.out.println(token);
        }
    }
    reader.close();
File txt=新文件(“File.txt”);
扫描仪扫描=新扫描仪(txt);
ArrayList数据=新的ArrayList();
while(scan.hasNextLine()){
data.add(scan.nextLine());
}
系统输出打印项次(数据);
String[]simpleArray=data.toArray(新字符串[]{});

为什么要使用阵列?为什么不使用其他容器呢?因为我的老师说必须使用数组来存储txt文件数据伟大的老师,伟大的学生如果只允许使用数组(或者您正在用C或其他语言编程),您确实会这样做。或者,您可以模拟
List
所做的事情,并根据需要增加数组的大小,使用arrayCopy()复制所有项目,避免了两次读取文件的昂贵操作(尽管如果是一个小文件,它不会很重要)。这很有效!感谢另外,虽然((String line=abc.readLine())不起作用,但它应该是字符串行;而((line=abc.readLine())则可以起作用:]
File txt = new File("file.txt");
Scanner scan = new Scanner(txt);
ArrayList<String> data = new ArrayList<String>() ;
while(scan.hasNextLine()){
    data.add(scan.nextLine());
}
System.out.println(data);
String[] simpleArray = data.toArray(new String[]{});