使用java中的文件

时间:2012-12-26 21:25:01

标签: java file-io

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

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

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

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

5 个答案:

答案 0 :(得分: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();

还要考虑以下事项:

答案 1 :(得分: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();
    }
}

此代码段假定字符串数组不包含任何换行符,因为它用于分隔每个&#34;行&#34;在文件中。

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

如果你真的希望load file方法返回一个字符串数组,那么你可能需要调用output.toArray()方法并将其转换为String[]

答案 2 :(得分:1)

写入文件并从文件中读取

从文件中读取

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

现在BufferedReader将把FileReader作为参数,而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包含文件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(); } 的第一行。

假设您想将文件中的整行写入数组。你所要做的就是使用while循环和EOF作为哨兵:

BufferedReader

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

写入文件

我们使用PrintWriter代替FileReader,而不是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();

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

main.o

如果不关闭out文件,则输出文件中不会显示任何内容。希望这会有所帮助。

答案 3 :(得分: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();

答案 4 :(得分:0)

这里有两个问题:

  1. 管理文件(如果不存在则创建,如果存在则附加)
  2. 确保正确完成文字的撰写和阅读

  3. 1)管理文件

    [注意这个例子假定Java 6;如果使用Java 7,则可以使用try-with-resources feature]

    在阅读文件时,您必须检查文件是否存在。但是,在编写文件时,您可以使用FileOutputStream的构造函数来表示如果文件存在则附加到该文件。


    2)正确阅读和写作

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

    如果您总是要在默认字符编码相同的系统上运行代码,那么您可以使用简单的FileWriter / FileReader构造函数。但是,如果要使用具有(可能)不同默认编码的不同操作系统,则需要指定要使用的编码。要执行此操作,请使用带有流和字符集的OutputStreamWriter constructorInputStreamReader constructor。这允许您指定要使用的编码。


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