1. 用 PrintWriter 类输出,该类是向文本文件写入时常用的流类,主要代码为:
- PrintWriter writer = null;
- try {
- writer = new PrintWriter(new FileOutputStream("out.txt"));
- } catch (FileNotFoundException e) {
- System.out.println("Error opening the file out.txt.");
- System.exit(0);
- }
- writer.println("需要写入文件的字符");
- writer.close();
上面的方式将一个文件连接到一个流时,程序都是以空文件开始的。如果已经存在 out.txt 文件了,原内容会丢失;如果不存在,则会自动创建一个新的 out.txt 文件,再写入数据。
当然,如果想在原内容后追加,则需要添加一个参数,如下:
- writer = new PrintWriter(new FileOutputStream("out.txt", true));
- // 官方解释:if true, then bytes will be written to the end of the file rather than the beginning
2. 用 FileOutputStream 类输出,上面方式是用 FileOutputStream 类创建了一个可以用作 PrintWriter 构造器实参的流,而下面直接输出字节流,主要代码如下:
- FileOutputStream out = null;
- File file = new File("123.txt");
- if (file.exists()) {
- System.out.println("123.txt已存在!");
- try {
- out = new FileOutputStream(file, true);
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- }
- StringBuffer sb = new StringBuffer();
- DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
- sb.append("\r\n" + df.format(new Date()));
- byte[] b = "需要写入文件的字符".getBytes();
- try {
- out.write(b);
- out.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- } else {
- try {
- file.createNewFile();
- System.out.println("123.txt创建成功!");
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
3. 用 BufferedReader 类从文本文件中读取数据。主要代码为:
- try {
- BufferedReader in = new BufferedReader(new FileReader("data.txt"));
- String line = null;
- line = in.readLine();
- System.out.println("读入的字符串为:" + line);
- in.close();
- } catch (FileNotFoundException e) {
- System.out.println("File data.txt was not found or could not be opened.");
- } catch (IOException e) {
- System.out.println("Error reading from file data.txt.");
- }