提示我路径未找到,文件名是自己键入的,代码如下:
public class CSVParser extends ConsoleProgram {
public void run(){
ArrayList<String> result = new ArrayList<String>();
String filename = openfile("Enter the filename :");
int columnIndex = readInt("Enter the column index :");
result = extractColumn(filename,columnIndex);
println(result);
}
//读取文件,若文件不存在则提示,重新键入文件名
private String openfile(String prompt){
BufferedReader rd = null;
while(rd==null){
try{
String name = readLine(prompt);
rd = new BufferedReader(new FileReader(name));
}catch(IOException e){
println("bad file.The file doesn't exist.");
}
}
return getName();
}
//根据文件名和所要获取的列数输出该列所有内容
private ArrayList extractColumn(String filename, int columnIndex) {
ArrayList result = new ArrayList();
try {
BufferedReader rd = new BufferedReader(new FileReader(filename));
String line="";
while((line = rd.readLine()) != null){
String str = (fieldsIn(line).get(columnIndex-1));
result.add(str);
}rd.close();
}catch (IOException e){
e.printStackTrace();
throw new RuntimeException(e);
}
return result;
}
}