开发者社区 问答 正文

Java filenotfoundexception问题

提示我路径未找到,文件名是自己键入的,代码如下:

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;
}
}

展开
收起
蛮大人123 2016-02-26 16:39:12 2760 分享 版权
1 条回答
写回答
取消 提交回答
  • 我说我不帅他们就打我,还说我虚伪

    工具是最公正的,有异常还是说明程序本身有问题。你检查下输入的文件路径是否正确。文件路径中统一用“/"。
    试一下绝对路径

    /** 获得文件名称 **/
        public String getFile(){
            File file = null;
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 
            String readLine = "";
            try {
                while( (readLine=br.readLine())!=null ){
                    file = new File(readLine);
                    /// 判断文件存在,并且是一个文件 ///
                    if(file.exists() && file.isFile()){
                        break;
                    }else{
                        System.out.println("该文件不存在。");
                    }
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return file.getName();
        }
    2019-07-17 18:48:24
    赞同 展开评论
问答分类:
问答标签:
问答地址: