【问题标题】:Java - creating new file, how do I specify the directory with a method?Java - 创建新文件,如何使用方法指定目录?
【发布时间】:2011-09-15 00:23:45
【问题描述】:

我知道如何通过这样做将file 写入指定目录:

 public void writefile(){

    try{
        Writer output = null;
        File file = new File("C:\\results\\results.txt");
        output = new BufferedWriter(new FileWriter(file));

        for(int i=0; i<100; i++){
           //CODE TO FETCH RESULTS AND WRITE FILE
        }

        output.close();
        System.out.println("File has been written");

    }catch(Exception e){
        System.out.println("Could not create file");
    }

但是,如果在方法中设置了目录,我该如何继续指定目录?例如,一个名为getCacheDirectory() 的方法。假设所有必要的导入等都已完成..

谢谢:)。

【问题讨论】:

    标签: java file io directory


    【解决方案1】:

    你的意思是

        File file = new File(getCacheDirectory() + "\\results.txt");
    

    如果getCacheDirectory() 将路径返回为String,那就对了;如果它返回一个File,那么有一个不同的构造函数:

        File file = new File(getCacheDirectory(), "results.txt");
    

    【讨论】:

    • 最好不要硬编码文件分隔符,在第一种情况下使用File file = new File(new File(getCacheDirectory()), "results.txt");。
    • 确实,我只是想做一些 OP 会立即识别并“得到”的事情。
    • 在这种情况下是否仍然可以将文件名作为相对路径?示例:文件 file = new File(new File(getCacheDirectory()), "..\\..\\files\\results.txt");
    猜你喜欢
    • 2016-08-04
    • 2012-11-28
    • 2012-11-20
    • 1970-01-01
    • 1970-01-01
    • 2013-09-08
    • 1970-01-01
    • 2020-01-18
    相关资源
    最近更新 更多