Java - 创建新文件,如何使用方法指定目录? [英] Java - creating new file, how do I specify the directory with a method?

查看:118
本文介绍了Java - 创建新文件,如何使用方法指定目录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道如何通过以下方式将文件写入指定的目录:

I know how to write a file to a specified directory by doing this:

 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()的方法。假设所有必要的导入等都已经完成了。

But how do I go on specifying the directory, if the directory is set in a method? A method called getCacheDirectory() for example. Assuming that all necessary imports etc have been done..

谢谢:)。

推荐答案

你的意思是只是

You mean just

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

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

That would be right if getCacheDirectory() returned the path as a String; if it returned a File, then there's a different constructor for that:

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

这篇关于Java - 创建新文件,如何使用方法指定目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆