有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java无法找到并加载CSV文件

由于某种原因,虽然我已经下载了CSV文件,但我的程序无法读取它们。下面是我的代码,它会检查CSV文件是否存在。如果没有,它会转到URL,下载并读取代码。但是,它总是重新下载代码,尽管它位于path文件夹中

 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:\Users\n\u 000\workspace\Program\GOOG。csv 需要从网上下载。 正在查找路径C:\Users\n\u 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";

共 (1) 个答案

  1. # 1 楼答案

    它工作正常,我没有发现任何问题,我正在发布我的测试代码,希望它可能有用

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