2016-04-24 83 views
0

由于某些原因,尽管我已经下载了CSV文件,但我的程序无法读取它们。我的代码在下面,它检查CSV文件是否存在。如果没有,它会转到URL并下载并读取代码。但是,它始终会重新下载代码,尽管它位于路径文件夹中。Java - 无法找到并加载CSV文件

private void loadData(String path, String url) throws IOException{ 

    File f = new File(path); 
    System.out.println("looking for path " + path); 
    if(f.exists()) { 
     readSavedFile(path); //method to load data 
    } 
    else{ 
     System.out.println("Need to download from internet"); 
     downloadAndRead(url, path); 
    } 

}

此代码输出

寻找路径C:\用户\ n_000 \工作区\程序\ GOOG.csv 需要从互联网上下载。 寻找路径C:\ Users \ n_000 \ workspace \ Program \ CHK.csv 需要从网上下载。

,我使用创建路径的代码是这样的:

 String save = "filename"; //in program use this is the name of the stock eg GOOG or CHK 
     Path currentRelativePath = Paths.get(""); 
     String savedFolder = currentRelativePath.toAbsolutePath().toString() + "\\"; 

     path = savedFolder+save+".csv"; 
+0

您确定有'C:\ Users \ n_000 \ workspace \ Program \ GOOG.csv'吗? – 2016-04-24 13:37:18

+2

exists()可能由于各种原因(如权限或呼叫失败)返回false。 –

+0

@RC。我肯定该文件存在 – jonbon

回答

0

它的做工精细,我没有看到任何问题,我张贴我的测试代码,希望对大家有用。

import java.io.File; 
import java.io.IOException; 
import java.nio.file.Path; 
import java.nio.file.Paths; 

public class Test { 

    public static void main(String ar[]) 
    { 
     Test test=new Test(); 
    } 
    public Test() 
    { 
     String save = "GOOG"; //in program use this is the name of the stock eg GOOG or CHK 
     Path currentRelativePath = Paths.get(""); 
     String savedFolder = currentRelativePath.toAbsolutePath().toString() + "\\"; 
     String path = savedFolder+save+".csv"; 
     String url=null; 

     try 
     { 
      loadData(path,url); 

     } catch (IOException e) 
     { 
      e.printStackTrace(); 
     } 
    } 


    private void loadData(String path, String url) throws IOException 
    {  
     File f = new File(path); 
     System.out.println("looking for path " + path); 
     if(f.exists()) { 
      readSavedFile(path); //method to load data 
     } 
     else{ 
      System.out.println("Need to download from internet"); 
      downloadAndRead(url, path); 
     } 
    } 
    public void readSavedFile(String path) 
    { 
     System.out.println("Reading file"); 
    } 

    public void downloadAndRead(String url,String path) 
    { 
     System.out.println("Downloding file"); 
    } 
}