在java中使用文件 [英] Working with files in java

查看:170
本文介绍了在java中使用文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



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

插入和使用数组不是问题,但问题是我如何处理这些文件?如何创建一个新的文本文件(如果不存在),我该如何写入,如何从中读取?

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

下面是一个写入文本文件的例子:

  File file = new文件( ./ db.txt); 
PrintWriter pw = new PrintWriter(file,true); // true为自动刷新
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();






请考虑下列事项:




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.

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.

解决方案

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:

这篇关于在java中使用文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆