这是我的代码
package sequentialFilePractice;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
public class ReadFile{
static String line = "";
ReadFile() throws FileNotFoundException{
readTheFile();
CSVtoArrayList();
}
public String readTheFile() throws FileNotFoundException{
String csvFile = "H:\\S6\\AH Computing\\Java Practice\\test.csv";
BufferedReader br = null;
String cvsSplitBy = ",";
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return line;
}
public static ArrayList<String> CSVtoArrayList() {
ArrayList<String> splitCSV = new ArrayList<>();
if (line != null) {
String[] splitData = line.split("\\s*,\\s*");
for (int i = 0; i < splitData.length; i++) {
if (!(splitData[i] == null) || !(splitData[i].length() == 0)) {
splitCSV.add(splitData[i].trim());
}
}
}
for(int j = 0;j < splitCSV.size();j++){
System.out.println(splitCSV.get(j));
}
return splitCSV;
}
public static void main(String[]args) throws IOException{
ReadFile f = new ReadFile();
}
}
代码编译,文件存在。我可以打印行并打印文件的内容但是当我打印arrayList时,没有输出任何内容,所以它没有被复制。这是我第一次在java中使用顺序文件。
答案 0 :(得分:0)
您是否必须手动阅读该文件?如果没有,您应该查看http://opencsv.sourceforge.net/,它允许您直接将CSV读取到List<String[]>
,而不必处理循环管理,拆分行并创建列表。
实质上将代码缩减为:
CSVReader reader = new CSVReader(new FileReader("yourfile.csv"));
List myEntries = reader.readAll();