将文件保存到 Java 中的特定目录?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6366743/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Saving files to a specific directory in Java?
提问by NSP
This is probably a silly question, but I'm pretty new to Java and I can't figure it out.
Basically, I'm trying to download some files from a website and I want to save them to a particular folder (rather than the default of the same folder that my Java file is located in). How can I do this?
这可能是一个愚蠢的问题,但我对 Java 很陌生,我无法弄清楚。
基本上,我试图从网站下载一些文件,我想将它们保存到特定文件夹(而不是我的 Java 文件所在的同一文件夹的默认文件夹)。我怎样才能做到这一点?
I've been using FileReader
, BufferedReader
, BufferedInputStream
, and FileOutputStream classes
.
我已经使用了FileReader
,BufferedReader
,BufferedInputStream
,和FileOutputStream classes
。
Thanks :)
谢谢 :)
采纳答案by Bohemian
Java is pretty friendly with IO. Try something like this:
Java 对 IO 非常友好。尝试这样的事情:
File file = new File("/some/absolute/path/myfile.ext");
OutputStream out = new FileOutputStream(file);
// Write your data
out.close();
Notes:
笔记:
- Your program needs permission to write to the directory.
- If the first character of your path string is not
/
, it will be relative to your "current" directory - If you're writing text, you might find a
BufferedWriter
easier:BufferedWriter writer = new BufferedWriter(new FileWriter(file));
. It hasnewLine()
andwrite(String)
methods
- 您的程序需要写入目录的权限。
- 如果您的路径字符串的第一个字符不是
/
,它将相对于您的“当前”目录 - 如果您正在编写文本,您可能会发现一个
BufferedWriter
更简单的方法:BufferedWriter writer = new BufferedWriter(new FileWriter(file));
. 它有newLine()
和write(String)
方法
回答by Asaph
When you insantiate your FileOutputStream
you can pass an absolute path to the constructor. Like this:
当您实例化时,您FileOutputStream
可以将绝对路径传递给构造函数。像这样:
FileOutputStream os = new FileOutputStream("/path/to/file.txt");
回答by Akash Roy
FileOutputStream os = new FileOutputStream("//path//to//file.txt");
this will work as putting
这将作为把
//在一个
""将作为'/'。因为我们在地址栏中使用它。