我不明白为什么这段代码不能读取.txt文件然后将其转换为数组。我没有开始的确切行数(设置数组)所以我用while循环计算.txt文件行。 该程序应计算它导入的行数,然后创建一个要复制的新数组。将信息打印到控制台。
public class Cre{
public void openFile() throws IOException{
BufferedReader in = new BufferedReader(new FileReader("C:\\Users\\file.txt"));
String line = in.readLine();
int i=0;
String linecounterguy = "null";
int count = 0;
while(line!= null) { ///to count number of rows///
linecounterguy = in.readLine();
count += 1;
}
String[] array = new String[count+1];
String line1 = "try";
while(line!= null)
{
line1 = in.readLine();
System.out.println(line1);
}
in.close();
for (int j = 0; j < array.length-1 ; j++) {
linecounterguy = in.readLine();
System.out.println(array[j]);
}
}
}
主类
> public class JavaApplication8 {
>
> /**
> * @param args the command line arguments
> */
> public static void main(String[] args) throws IOException {
>
>
> Cre k = new Cre();
> k.openFile();
>
>
> } }
答案 0 :(得分:0)
这是一个小方法,可以帮助您开始将文本文件读入字符串数组。希望这有帮助!
public String[] readLines(String filename) throws IOException {
FileReader fileReader = new FileReader(filename);
BufferedReader bufferedReader = new BufferedReader(fileReader);
List<String> lines = new ArrayList<String>();
String line = null;
while ((line = bufferedReader.readLine()) != null) {
lines.add(line);
}
bufferedReader.close();
return lines.toArray(new String[lines.size()]);
}