利用 Java io 包进行文件读写操作

2017-10-30

前些天面试的时候考了两道题,都是有关 Java 基础的:

  • 利用 Java io 包进行读写文件;
  • 使用 JDBC 获取数据。

很可惜当时记不起来这些基础知识,所以很有必要整理一下,巩固一下这方面的知识。

在这篇总结里,我将通过代码,文字解释两部分来总结 io 包的读写文件操作。


场景

例如在桌面上有一份 1.txt 文件,里面是一行以半角逗号分隔的乱序数字。请编写 Java 程序读取该文件,并降序排序,写到 2.txt 文件中(若没有就新建)。限用 io 包。

考察知识点

  • 读取文件
  • 字符串与整型数组之间的转换
  • 排序算法
  • 写文件

代码示例

我也将代码托管在码云平台,可以前往参考:https://gitee.com/jinglun404/io-demo

  1 import java.io.*;
  2 
  3 public class Main {
  4 
  5     public static void main(String[] args) {
  6         String filePath = "C:\\Users\\ASUSS\\Desktop\\1.txt";
  7 
  8         readFile(filePath);
  9     }
 10 
 11     // 读取文件方法
 12     public static void readFile(String filePath) {
 13         try {
 14             String encoding = "UTF-8";
 15             // 1.获得File对象
 16             File file = new File(filePath);
 17 
 18             if (file.isFile() && file.exists()) { // 判断文件是否存在
 19                 // 2.File对象->FileInputStream对象->InputStreamReader对象
 20                 InputStreamReader read = new InputStreamReader(new FileInputStream(file), encoding);
 21                 System.out.println("read:" + read); //read:java.io.InputStreamReader@14ae5a5
 22 
 23                 // 3.通过InputStreamReader对象获得BufferedReader对象
 24                 BufferedReader bufferedReader = new BufferedReader(read);
 25                 System.out.println("bufferedReader:" + bufferedReader); //bufferedReader:java.io.BufferedReader@7f31245a
 26 
 27                 // 4.通过BufferedReader对象将文件内容以字符串形式读出
 28                 String lineText = null;
 29                 while ((lineText = bufferedReader.readLine()) != null) {
 30                     System.out.println("lineText:" + lineText); //lineText:1,1,4,5,23,12,13,35,345,34,67,5,3,90
 31 
 32                     // 将读取的字符串根据“,”分割成字符串数组
 33                     String[] stringNums = lineText.split(",");
 34 
 35                     // 将字符串数组转换成整型数组,用于排序
 36                     int[] intNums = new int[stringNums.length];
 37                     for (int i = 0; i < stringNums.length; i++) {
 38                         intNums[i] = new Integer(stringNums[i]);
 39                     }
 40 
 41                     // 调用排序方法
 42                     mySort(intNums);
 43 
 44                     // 将整型数组转换成字符串,用于写入文件
 45                     String s = "";
 46                     for (int i = 0; i < intNums.length; i++) {
 47                         s += intNums[i] + ",";
 48                     }
 49                     s = s.substring(0, s.length()-1);// 去掉最后一个“,”
 50 
 51                     // 调用写文件方法
 52                     writeFile(s);
 53                 }
 54                 read.close();
 55 
 56             } else {
 57                 System.out.println("找不到指定文件!");
 58             }
 59         } catch (Exception e) {
 60             System.out.println("读取文件出错!");
 61             e.printStackTrace();
 62         }
 63     }
 64 
 65     // 写入文件方法
 66     private static void writeFile(String s) {
 67         String writeFile = "C:\\Users\\ASUSS\\Desktop\\2.txt";
 68 
 69         // 1.获得File对象
 70         File newFile = new File(writeFile);
 71 
 72         try {
 73             if (!newFile.exists()) {
 74                 // 若文件不存在,则新建文件
 75                 newFile.createNewFile();
 76             }
 77 
 78             // 2.通过File对象获得FileOutputStream对象
 79             FileOutputStream out = new FileOutputStream(newFile, true);
 80             StringBuffer sb = new StringBuffer();
 81             sb.append(s);
 82 
 83             // 3.通过FileOutputStream进行写操作
 84             out.write(s.toString().getBytes("UTF-8"));
 85             out.close();
 86         } catch (IOException e) {
 87             e.printStackTrace();
 88         }
 89     }
 90 
 91     // 冒泡排序,降序输出
 92     private static void mySort(int[] intNums) {
 93         int temp = 0;
 94         for (int i = 0; i < intNums.length; i++) {
 95             for (int j = 0; j < intNums.length - i - 1; j++) {
 96                 if (intNums[j] < intNums[j + 1]) {
 97                     temp = intNums[j];
 98                     intNums[j] = intNums[j + 1];
 99                     intNums[j + 1] = temp;
100                 }
101             }
102         }
103     }
104 }

说明

读取文件

利用 Java 的 io 包读取文件内容,分为几个步骤:

  1. 传入文件路径生成 File 对象实例
  2. 通过 File 实例生成 FileInputStream 对象实例
  3. 通过 FileInputStream 对象实例生成 InputStreamReader 对象实例
  4. 通过 InputStreamReader 对象实例生成 BufferedReader 对象实例
  5. 通过 BufferedReader 对象实例的 .readLine() 方法读取文件的一行数据

一般步骤如上,但为何要这样做呢?我的理解如下:

  1. Java 的文件操作都是基于 File 对象的,因此读取文件操作的第一步肯定是获取一个 FIle 对象实例,那么获取怎样的实例呢?由此很容易联想到需要获取我们进行读取的文件的 File 实例。所以这里便需要传入文件路径参数,来构造出一个 File 实例。
  2. 获取了 File 的实例,我们的 Java 程序便与文件取得了联系,接下来需要将文件读入到内存中,方便我们的 Java 程序进行后续操作。
  3. 通过生成 FileInputStream 对象实例,我们将文件内容以字节形式写入到内存。
  4. 但我们读不懂字节内容,因此不能直接输出存到内存中的字节内容。需要进行继续转换。
  5. 通过生成 InputStreamReader 对象实例,我们读取了内存中的字节内容,然后进一步生成 BufferedReader 对象实例,将字节内容放在缓存区,加快操作的速度。
  6. 最后,利用 BufferedReader 的 .readLine() 方法,将字节转换成我们能读懂的字符串信息,进行输出。

写入文件

利用 Java io 包进行写入文件,操作思路跟读取文件类似,甚至简单些,例如:

  1. 获取 File 对象实例
  2. 通过 File 实例获取 FileOutputStream 对象实例
  3. 利用 FileOutputStream 的 .write() 方法将字节数据写入文件

当然这只是大概思路。具体实现过程可以参考我的代码逻辑。

排序逻辑

对数字进行排序,实现的方法很多,我这里使用了常见的冒泡排序,具体不展开讲了,网上也有很多资料。也可以参考我代码的逻辑。

 

参考网站

http://www.cnblogs.com/manongxiaojiang/archive/2012/10/13/2722068.html
https://segmentfault.com/q/1010000000359840
https://www.ezloo.com/2008/03/jave_file_reader_writer.html

 

posted on 2017-10-30 10:02  陈加菲  阅读(4171)  评论(0编辑  收藏  举报

导航