Java - 创建新文件,如何使用方法指定目录?
我知道如何通过执行以下操作将 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()
的方法。假设所有必要的导入等都已完成..
谢谢:)。
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");
}
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..
Thanks :).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的意思是
,如果
getCacheDirectory()
将路径作为String
返回,那就对了;如果它返回一个File
,那么有一个不同的构造函数:You mean just
That would be right if
getCacheDirectory()
returned the path as aString
; if it returned aFile
, then there's a different constructor for that: