在 Java 中创建文件并写入文件的最佳方法是什么
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26380744/
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
Which is the best way to create file and write to it in Java
提问by Simple-Solution
I normally use PrintWritter
object to create and write to a file, but not sure if its the best in terms of speed and security compare to other ways of creating and writing to a file using other approaches i.e.
我通常使用PrintWritter
对象来创建和写入文件,但不确定与使用其他方法创建和写入文件的其他方法相比,它在速度和安全性方面是否最好,即
Writer writer = new BufferedWriter(
new OutputStreamWriter(
new FileOutputStream("example.html"), "utf-8"));
writer.write("Something");
vs
vs
File file = new File("example.html");
BufferedWriter output = new BufferedWriter(new FileWriter(file));
output.write("Something");
vs
vs
File file = new File("example.html");
FileOutputStream is = new FileOutputStream(file);
OutputStreamWriter osw = new OutputStreamWriter(is);
Writer w = new BufferedWriter(osw);
w.write("something");
vs
vs
PrintWritter pw = new PrintWriter("example.html", "UTF-8");
pw.write("Something");
Also, when to use one over the other; a use case scenario would be appreciated. I'm not asking for how to create and write to file, I know how to do that. Its more of compare and contrast sort of question I'm asking.
此外,何时使用一个而不是另一个;用例场景将不胜感激。我不是在问如何创建和写入文件,我知道该怎么做。我问的更多是比较和对比类型的问题。
回答by Eng.Fouad
I prefer:
我更喜欢:
boolean append = true;
boolean autoFlush = true;
String charset = "UTF-8";
String filePath = "C:/foo.txt";
File file = new File(filePath);
if(!file.getParentFile().exists()) file.getParentFile().mkdirs();
FileOutputStream fos = new FileOutputStream(file, append);
OutputStreamWriter osw = new OutputStreamWriter(fos, charset);
BufferedWriter bw = new BufferedWriter(osw);
PrintWriter pw = new PrintWriter(bw, autoFlush);
pw.write("Some File Contents");
which gives you:
这给了你:
- Decide whether to append to the text file or overwrite it.
- Decide whether to make it auto-flush or not.
- Specify the charset.
- Make it buffered, which improves the streaming performance.
- Convenient methods (such as
println()
and its overloaded ones).
- 决定是附加到文本文件还是覆盖它。
- 决定是否让它自动刷新。
- 指定字符集。
- 使其缓冲,从而提高流媒体性能。
- 方便的方法(例如
println()
及其重载的方法)。
回答by Clemencio Morales Lucas
Honestly, I don't know if this is the best option, but I think that is a System
like, common accepted abstraction:
老实说,我不知道这是否是最好的选择,但我认为这是一个System
类似的、普遍接受的抽象:
In.java:
在.java中:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class In {
public In() {
}
/**
* Tranforms the content of a file (i.e: "origin.txt") in a String
*
* @param fileName: Name of the file to read
* @return String which represents the content of the file
*/
public String readFile(String fileName) {
FileReader fr = null;
try {
fr = new FileReader(fileName);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
BufferedReader bf = new BufferedReader(fr);
String file = "", aux = "";
try {
while ((file = bf.readLine()) != null) {
aux = aux + file + "\n";
}
bf.close();
} catch (IOException e) {
e.printStackTrace();
}
return aux;
}
}
Out.java:
输出.java:
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class Out {
public Out() {}
/**
* Writes on the file named as the first parameter the String which gets as second parameter.
*
* @param fileName: Destiny file
* @param message: String to write on the destiny file
*/
public void writeStringOnFile(String fileName, String message) {
FileWriter w = null;
try {
w = new FileWriter(fileName);
} catch (IOException e) {
e.printStackTrace();
}
BufferedWriter bw = new BufferedWriter(w);
PrintWriter wr = new PrintWriter(bw);
try {
wr.write(message);
wr.close();
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
IO.java:
IO.java:
public class IO {
public Out out;
public In in;
/**
* Object which provides an equivalent use to Java 'System' class
*/
public IO() {
this.setIn(new In());
this.setOut(new Out());
}
public void setIn(In in) {
this.in = in;
}
public In getIn() {
return this.in;
}
public void setOut(Out out) {
this.out = out;
}
public Out getOut() {
return this.out;
}
}
Therefore, you can use the class IO
almost in the same way you will use System
.
因此,您IO
几乎可以像使用System
.
Hope it helps.
希望能帮助到你。
Clemencio Morales Lucas.
克莱门西奥·莫拉莱斯·卢卡斯。
回答by ursa
The best solution, as usual, depends on your task: either you work with text or with binary data. In the first case you should prefer writers, in the second - streams.
与往常一样,最佳解决方案取决于您的任务:您使用文本还是二进制数据。在第一种情况下,您应该更喜欢作家,在第二种情况下 - 流。
You ask for comparison of approaches to write TEXT into files.
您要求比较将 TEXT 写入文件的方法。
The last case in your question is the best one for writing/creation new text files. It is suitable for 99% of practical tasks.
您问题中的最后一个案例是编写/创建新文本文件的最佳案例。它适用于 99% 的实际任务。
PrintWritter pw = new PrintWriter("example.html", "UTF-8");
pw.write("Something");
It is short and readable. It supports explicit encoding and buffering. It does not require unnecessary wrappers.
它简短易读。它支持显式编码和缓冲。它不需要不必要的包装器。
Other old-fashion approaches can and should be used in those cases, where this solution is not applicable. E.g. you want to append any text to file. In this case you have no choice except to use writers based on stream wrappers (unfortunately, FileWriter doesn't support explicit encoding).
在这种解决方案不适用的情况下,可以而且应该使用其他老式方法。例如,您想将任何文本附加到文件中。在这种情况下,您别无选择,只能使用基于流包装器的编写器(不幸的是,FileWriter 不支持显式编码)。