我正在尝试编写一个逐行读取texfile的java程序,并将每一行存储在自己的数组中,以便这些行成为数据列。例如,下面的data.txt文件包含以下数据:
我希望每一行都存储在自己的数组中,因此4行,4个不同的数组,因为每行都属于一个特定的列。 我能够阅读文本文件。
BufferedReader br = new BufferedReader(new FileReader("C://data.txt"));
ArrayList lines = new ArrayList();
for(String line = br.readLine();line != null;line = br.readLine()) {
line.replaceAll(",","\\.");
String[] fields = line.split(" ");
System.out.println(" " + fields[0]);
lines.add(fields);
}
String[][] strings = (String[][]) lines.toArray(new String[lines.size()][]);
System.out.println("Total Lines: " + strings.length);
这是预期的输出:
答案 0 :(得分:0)
如果您想要特定阵列中的每一行,那么以下内容应该有帮助
BufferedReader br = new BufferedReader(new FileReader("C:\\data.txt"));
ArrayList lines = new ArrayList();
for(String line = br.readLine();line != null;line = br.readLine()) {
//comma will be replaced with .
line=line.replaceAll(",","\\.");
//each line will be stored in an array with . as separator
String[] fields = line.split("\\.");
//System.out.println(" " + fields[0]);
lines.add(fields);
}
String[][] strings = (String[][]) lines.toArray(new String[lines.size()][]);
System.out.println("Total Lines: " + strings.length);
//code to display
for(String s[]:strings){
for(String ss:s){
System.out.print(ss+", ");
}System.out.println();
}
其输出
Total Lines: 4
122, 80, 100, 119, 162, 90, 136,
122, 80, 100, 119, 162, 90, 136,
64, 74, 70, 64, 76, 62, 84, 78 ,
positive, negative, negative ,
答案 1 :(得分:0)
我认为这就是你所需要的:
$file = fopen("contacts.csv","a");