在 Java 中处理文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14046445/
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
Working with files in java
提问by Jjang
I have an array of strings. I want to save those strings in a file. The problem is, I need to make a new file called db.txt (only if it doesn't exist), then somehow write strings to it.
我有一个字符串数组。我想将这些字符串保存在一个文件中。问题是,我需要创建一个名为 db.txt 的新文件(仅当它不存在时),然后以某种方式向其中写入字符串。
And then later I want to be able to read strings from that file and insert them to the array.
然后我希望能够从该文件中读取字符串并将它们插入到数组中。
Inserting and using array is not the question, but the question is how do I mess with the files? How do I create a new text file (if not existing already), how do I write to it and how do I read from it?
插入和使用数组不是问题,但问题是我如何弄乱文件?如何创建新的文本文件(如果尚不存在),如何写入以及如何从中读取?
Tried to learn it by myself but I've seen so many ways on the Internet and got confused.
试图自己学习它,但我在互联网上看到了很多方法并且感到困惑。
回答by Eng.Fouad
Here is an example of writing to a text file:
这是写入文本文件的示例:
File file = new File("./db.txt");
PrintWriter pw = new PrintWriter(file, true); // true for auto-flush
pw.println("Line 1");
pw.println("Line 2");
pw.println("Line 3");
pw.close();
In case you want to append to existing text file:
如果您想附加到现有的文本文件:
File file = new File("./db.txt");
FileWriter fw = new FileWriter(file, true); // true for appending
PrintWriter pw = new PrintWriter(fw, true); // true for auto-flush
pw.println("Line 4");
pw.println("Line 5");
pw.println("Line 6");
pw.close();
To read from text file:
从文本文件中读取:
File file = new File("./db.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String line1 = br.readLine();
String line2 = br.readLine();
String line3 = br.readLine();
br.close();
Also consider the following:
还要考虑以下几点:
PrintWriter
does not create new file if it does not exist, whileFileWriter
does.- To check if a file exists, use:
file.exists()
. - To check if the file object refers to a file or a directory, use:
file.isDirectory()
andfile.isFile()
. - To create a new file, use:
file.createNewFile()
. - To create a directory, use:
file.mkdirs()
. - You may need to use the constructors
PrintWriter(File file, String csn)
andInputStreamReader(InputStream in, Charset cs)
to determine the charset.
PrintWriter
如果不存在,则FileWriter
不会创建新文件,而会。- 要检查文件是否存在,请使用:
file.exists()
。 - 要检查文件对象是指文件还是目录,请使用:
file.isDirectory()
和file.isFile()
。 - 要创建新文件,请使用:
file.createNewFile()
. - 要创建目录,请使用:
file.mkdirs()
。 - 您可能需要使用构造函数
PrintWriter(File file, String csn)
并InputStreamReader(InputStream in, Charset cs)
确定字符集。
回答by Spoike
If you're going to save an array of strings to an file then this is how you do it:
如果您要将字符串数组保存到文件中,那么您可以这样做:
public void saveToFile(Iterable<String> stringArray, String pathName) {
File f = new File(pathName);
try {
FileWriter fileWriter = new FileWriter(f);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
for (String s : stringArray) {
bufferedWriter.write(s);
bufferedWriter.newLine();
bufferedWriter.flush();
}
bufferedWriter.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
This snippet assumes that the string array does not contain any newline characters as it is used to seperate each "line" in the file.
此代码段假定字符串数组不包含任何换行符,因为它用于分隔文件中的每个“行”。
public Iterable<String> loadFile(String pathName) {
File f = new File(pathName);
ArrayList<String> output = new ArrayList<String>();
try {
Scanner scanner = new Scanner(f);
String str = scanner.nextLine();
while (str != null) {
output.add(str);
scanner.nextLine();
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}
return output;
}
If you really want the load file method to return a string array then you might need to call the output.toArray()
method and typecast that to String[]
.
如果您真的希望加载文件方法返回一个字符串数组,那么您可能需要调用该output.toArray()
方法并将其类型转换为String[]
.
回答by Wizzy232
Writing to a File and Reading from a file
写入文件和读取文件
Reading from a file
从文件中读取
If you want to read from a file, you need to import the BufferedReader
class from the java.io.*
package.
如果要从文件中读取,则需要BufferedReader
从java.io.*
包中导入类。
Now the BufferedReader
will take as argument a FileReader
which in turn will take as argument the name of the file to read from. Let me show you this in code:
现在BufferedReader
将作为参数 a FileReader
,而后者将作为参数读取文件的名称。让我用代码向您展示这一点:
BufferedReader in = new BufferedReader(new FileReader("myFile.txt"));
Now the object in
can now perform some action on the file myFile.txt
.
So let's say I wanted the first line in myFile.txt
: I would use the readLine()
method.
现在对象in
现在可以对文件执行一些操作myFile.txt
。所以假设我想要第一行myFile.txt
:我会使用该readLine()
方法。
BufferedReader in = new BufferedReader(new FileReader("myFile.txt"));
String line1 = in.readLine();
Now line1
contains the first line of the file myfile.txt
.
现在line1
包含文件的第一行myfile.txt
。
Let's say you wanted to write the entire lines in a file to an array. All you have to do is use a while loop and the EOF as a sentinel:
假设您想将文件中的整行写入数组。您所要做的就是使用 while 循环和 EOF 作为哨兵:
ArrayList<String> fileLines = new ArrayList<String>();
BufferedReader in = new BufferedReader(new FileReader("myFile.txt"));
String currentLine = in.readLine();
while(currentLine != null){
fileLines.add(currentLine);
currentLine = in.readLine();
}
What that does is read every line of the file and write it to an array that can then be used for further processing.
这样做是读取文件的每一行并将其写入一个数组,然后可以用于进一步处理。
Writing to files
写入文件
Here instead of a BufferedReader
we use a PrintWriter
, and instead of a FileReader
we use a FileWriter
.
这里BufferedReader
我们使用 aPrintWriter
代替 a ,FileReader
我们使用 a代替a FileWriter
。
PrintWriter out = new PrintWriter(new PrintWriter("output.txt"));
Now if output.txt
has not been made beforehand, the program will automatically make a new one.
现在如果output.txt
没有事先制作,程序会自动制作一个新的。
So let's look at how it prints:
那么让我们看看它是如何打印的:
String wiseSaying = "This is not a wise saying";
PrintWriter out = new PrintWriter(new PrintWriter("output.txt"));
out.println(wiseSaying);
That prints the value of wiseSaying
to the file output.txt
.
将 的值打印wiseSaying
到文件中output.txt
。
Now you have to close both files when you are done.
现在您必须在完成后关闭这两个文件。
in.close();
out.close();
If you don't close the out file, you will not see anything in your output file. Hope this helps.
如果您不关闭输出文件,您将不会在输出文件中看到任何内容。希望这可以帮助。
回答by AFS
To write to a file, use java.io.PrintWriter:
要写入文件,请使用 java.io.PrintWriter:
File myFile= new File("db.txt");
PrintWriter out = new PrintWriter(myFile);
//Now use out.print() and out.println() just
//as you would use System.out.print() and System.out.println()
out.print("test");
out.println();
out.close();
To read from a file, use java.io.Scanner:
要读取文件,请使用 java.io.Scanner:
File myFile = new File("db.txt");
Scanner s = new Scanner(myFile);
String n = s.next(); //gets you the next token;
String n = s.nextLine(); //gets you the next line as a string;
s.close();
回答by user1135122
There are two issues here:
这里有两个问题:
- Managing the file (creating if absent, appending if present)
- Making sure writing and reading your text is done correctly
- 管理文件(如果不存在则创建,如果存在则追加)
- 确保正确完成文本的书写和阅读
1) Managing the file
1) 管理文件
[Note the example assumes Java 6; if using Java 7, you can use the try-with-resources feature]
[注意该示例假定 Java 6;如果使用 Java 7,则可以使用try-with-resources 功能]
You will have to check for existence of the file when going to read it. However, when writing the file, you can use the constructor for FileOutputStream that says to append to the file if it exists.
阅读文件时,您必须检查该文件是否存在。但是,在写入文件时,您可以使用 FileOutputStream 的构造函数,该构造函数表示如果文件存在则追加到文件中。
2) Reading and writing correctly
2) 正确读写
For a robust solution, you need to watch out for character encoding issues. The whole Reader/Writer framework was introduced to fix character encoding issues with the Stream implementations (OutputStream/InputStream/etc.).
要获得可靠的解决方案,您需要注意字符编码问题。引入了整个 Reader/Writer 框架来修复 Stream 实现(OutputStream/InputStream/etc.)的字符编码问题。
If you are always going to run the code on systems where the default character encoding is the same, you can get away with using the simple FileWriter/FileReader constructors. However, if you are going to use different OSes with (possibly) different default encodings, you need to specify the encoding to use. To do this, you use the OutputStreamWriter constructoror InputStreamReader constructorthat takes a stream and a Charset. This allows you to specify the encoding to use.
如果您总是要在默认字符编码相同的系统上运行代码,则可以使用简单的 FileWriter/FileReader 构造函数。但是,如果您要使用具有(可能)不同默认编码的不同操作系统,则需要指定要使用的编码。为此,您可以使用采用流和字符集的OutputStreamWriter 构造函数或InputStreamReader 构造函数。这允许您指定要使用的编码。
package org.foo;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.Writer;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
public class FilesAndStrings {
final static String[] STRINGS = {"One", "Two", "Three"};
final static String FILE = "strings.txt";
final static Charset UTF8_CHARSET = Charset.forName("UTF-8");
public static void main(String[] args) throws IOException {
// Single argument decides whether we write to the file or read from it
if (args.length > 0) {
String[] whatWeRead = readStrings();
// Do something with whatWeRead
}
else {
writeStrings();
}
}
public static void writeStrings() throws FileNotFoundException {
OutputStreamWriter out = null;
BufferedWriter bw = null;
PrintWriter pw = null;
try {
out = new OutputStreamWriter(new FileOutputStream(FILE, true), UTF8_CHARSET);
bw = new BufferedWriter(out);
pw = new PrintWriter(bw);
for (String s : STRINGS) {
pw.println(s);
}
}
finally {
tryToClose(pw);
tryToClose(bw);
tryToClose(out);
}
}
public static String[] readStrings() throws IOException {
InputStreamReader in = null;
BufferedReader br = null;
try {
in = new InputStreamReader(new FileInputStream(FILE), UTF8_CHARSET);
br = new BufferedReader(in);
List<String> strings = new ArrayList<String>();
String s = br.readLine();
while (s != null) {
strings.add(s);
s = br.readLine();
}
return strings.toArray(new String[strings.size()]);
}
finally {
tryToClose(br);
tryToClose(in);
}
}
public static void tryToClose(final Writer w) {
try {
w.close();
}
catch (IOException e) {
// Log error
}
}
public static void tryToClose(final Reader r) {
try {
r.close();
}
catch (IOException e) {
// Log error
}
}
}