3

我有一个字符串数组。我想将这些字符串保存在文件中。问题是,我需要创建一个名为 db.txt 的新文件(仅当它不存在时),然后以某种方式向其中写入字符串。

然后稍后我希望能够从该文件中读取字符串并将它们插入到数组中。

插入和使用数组不是问题,但问题是我如何弄乱文件?如何创建一个新的文本文件(如果尚不存在),如何写入它以及如何读取它?

试图自己学习它,但我在互联网上看到了很多方法并且感到困惑。

4

5 回答 5

8

以下是写入文本文件的示例:

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();

如果您想附加到现有的文本文件:

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();

从文本文件中读取:

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();

还要考虑以下几点:

于 2012-12-26T21:30:29.207 回答
2

如果您要将字符串数组保存到文件中,那么您就是这样做的:

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();
    }
}

此片段假定字符串数组不包含任何换行符,因为它用于分隔文件中的每个“行”。

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;
}

如果您真的希望加载文件方法返回一个字符串数组,那么您可能需要调用该output.toArray()方法并将其类型转换为String[].

于 2012-12-26T21:32:39.647 回答
1

写入文件和读取文件

从文件中读取

如果要从文件中读取,则需要从包中导入BufferedReader类。java.io.*

现在BufferedReader将把 a 作为参数FileReader,而 a 又将要读取的文件的名称作为参数。让我用代码告诉你:

BufferedReader in = new BufferedReader(new FileReader("myFile.txt"));

现在对象in现在可以对文件执行一些操作了myFile.txt。所以假设我想要第一行myFile.txt:我会使用该readLine()方法。

BufferedReader in = new BufferedReader(new FileReader("myFile.txt"));
String line1 = in.readLine();

现在line1包含文件的第一行myfile.txt

假设您想将文件中的整行写入数组。您所要做的就是使用一个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();
}

这样做是读取文件的每一行并将其写入一个数组,然后可以用于进一步处理。

写入文件

这里BufferedReader我们使用 aPrintWriter而不是 a,我们使用 a 而不是FileReadera FileWriter

PrintWriter out = new PrintWriter(new PrintWriter("output.txt"));

现在如果output.txt没有事先制作,程序会自动制作一个新的。

那么让我们看看它是如何打印的:

String wiseSaying = "This is not a wise saying";
PrintWriter out = new PrintWriter(new PrintWriter("output.txt"));
out.println(wiseSaying);

这会将 的值打印wiseSaying到文件output.txt中。

现在您必须在完成后关闭这两个文件。

in.close();
out.close();

如果您不关闭输出文件,您将不会在输出文件中看到任何内容。希望这可以帮助。

于 2015-08-31T17:31:36.720 回答
0

要写入文件,请使用 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();

要从文件中读取,请使用 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();
于 2012-12-26T21:33:18.637 回答
0

这里有两个问题:

  1. 管理文件(如果不存在则创建,如果存在则追加)
  2. 确保正确书写和阅读文本

1) 管理文件

[请注意,该示例假定 Java 6;如果使用 Java 7,您可以使用try-with-resources 功能]

读取文件时,您必须检查文件是否存在。但是,在写入文件时,您可以使用 FileOutputStream 的构造函数,如果文件存在则追加到文件中。


2)正确读写

要获得强大的解决方案,您需要注意字符编码问题。引入了整个 Reader/Writer 框架来解决 Stream 实现(OutputStream/InputStream/etc.)的字符编码问题。

如果您总是要在默认字符编码相同的系统上运行代码,则可以使用简单的 FileWriter/FileReader 构造函数。但是,如果您要使用具有(可能)不同默认编码的不同操作系统,则需要指定要使用的编码。为此,您可以使用接受流和 Charset的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
        }
    }
}

于 2012-12-26T22:39:01.223 回答