2016-04-24 82 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"); 
    } 
}