[Java]读取文件方法大全

来源:互联网 发布:mac 装机软件 知乎 编辑:程序博客网 时间:2024/05/31 19:43
1、按字节读取文件内容
2、按字符读取文件内容
3、按行读取文件内容

4、随机读取文件内容 

  1. public class ReadFromFile {
  2.     /**
  3.      * 以字节为单位读取文件,常用于读二进制文件,如图片、声音、影像等文件。
  4.      */
  5.     public static void readFileByBytes(String fileName) {
  6.         File file = new File(fileName);
  7.         InputStream in = null;
  8.         try {
  9.             System.out.println("以字节为单位读取文件内容,一次读一个字节:");
  10.             // 一次读一个字节
  11.             in = new FileInputStream(file);
  12.             int tempbyte;
  13.             while ((tempbyte = in.read()) != -1) {
  14.                 System.out.write(tempbyte);
  15.             }
  16.             in.close();
  17.         } catch (IOException e) {
  18.             e.printStackTrace();
  19.             return;
  20.         }
  21.         try {
  22.             System.out.println("以字节为单位读取文件内容,一次读多个字节:");
  23.             // 一次读多个字节
  24.             byte[] tempbytes = new byte[100];
  25.             int byteread = 0;
  26.             in = new FileInputStream(fileName);
  27.             ReadFromFile.showAvailableBytes(in);
  28.             // 读入多个字节到字节数组中,byteread为一次读入的字节数
  29.             while ((byteread = in.read(tempbytes)) != -1) {
  30.                 System.out.write(tempbytes, 0, byteread);
  31.             }
  32.         } catch (Exception e1) {
  33.             e1.printStackTrace();
  34.         } finally {
  35.             if (in != null) {
  36.                 try {
  37.                     in.close();
  38.                 } catch (IOException e1) {
  39.                 }
  40.             }
  41.         }
  42.     }

  43.     /**
  44.      * 以字符为单位读取文件,常用于读文本,数字等类型的文件
  45.      */
  46.     public static void readFileByChars(String fileName) {
  47.         File file = new File(fileName);
  48.         Reader reader = null;
  49.         try {
  50.             System.out.println("以字符为单位读取文件内容,一次读一个字节:");
  51.             // 一次读一个字符
  52.             reader = new InputStreamReader(new FileInputStream(file));
  53.             int tempchar;
  54.             while ((tempchar = reader.read()) != -1) {
  55.                 // 对于windows下,\r\n这两个字符在一起时,表示一个换行。
  56.                 // 但如果这两个字符分开显示时,会换两次行。
  57.                 // 因此,屏蔽掉\r,或者屏蔽\n。否则,将会多出很多空行。
  58.                 if (((char) tempchar) != '\r') {
  59.                     System.out.print((char) tempchar);
  60.                 }
  61.             }
  62.             reader.close();
  63.         } catch (Exception e) {
  64.             e.printStackTrace();
  65.         }
  66.         try {
  67.             System.out.println("以字符为单位读取文件内容,一次读多个字节:");
  68.             // 一次读多个字符
  69.             char[] tempchars = new char[30];
  70.             int charread = 0;
  71.             reader = new InputStreamReader(new FileInputStream(fileName));
  72.             // 读入多个字符到字符数组中,charread为一次读取字符数
  73.             while ((charread = reader.read(tempchars)) != -1) {
  74.                 // 同样屏蔽掉\r不显示
  75.                 if ((charread == tempchars.length)
  76.                         && (tempchars[tempchars.length - 1!= '\r')) {
  77.                     System.out.print(tempchars);
  78.                 } else {
  79.                     for (int i = 0; i < charread; i++) {
  80.                         if (tempchars[i] == '\r') {
  81.                             continue;
  82.                         } else {
  83.                             System.out.print(tempchars[i]);
  84.                         }
  85.                     }
  86.                 }
  87.             }

  88.         } catch (Exception e1) {
  89.             e1.printStackTrace();
  90.         } finally {
  91.             if (reader != null) {
  92.                 try {
  93.                     reader.close();
  94.                 } catch (IOException e1) {
  95.                 }
  96.             }
  97.         }
  98.     }

  99.     /**
  100.      * 以行为单位读取文件,常用于读面向行的格式化文件
  101.      */
  102.     public static void readFileByLines(String fileName) {
  103.         File file = new File(fileName);
  104.         BufferedReader reader = null;
  105.         try {
  106.             System.out.println("以行为单位读取文件内容,一次读一整行:");
  107.             reader = new BufferedReader(new FileReader(file));
  108.             String tempString = null;
  109.             int line = 1;
  110.             // 一次读入一行,直到读入null为文件结束
  111.             while ((tempString = reader.readLine()) != null) {
  112.                 // 显示行号
  113.                 System.out.println("line " + line + "" + tempString);
  114.                 line++;
  115.             }
  116.             reader.close();
  117.         } catch (IOException e) {
  118.             e.printStackTrace();
  119.         } finally {
  120.             if (reader != null) {
  121.                 try {
  122.                     reader.close();
  123.                 } catch (IOException e1) {
  124.                 }
  125.             }
  126.         }
  127.     }

  128.     /**
  129.      * 随机读取文件内容
  130.      */
  131.     public static void readFileByRandomAccess(String fileName) {
  132.         RandomAccessFile randomFile = null;
  133.         try {
  134.             System.out.println("随机读取一段文件内容:");
  135.             // 打开一个随机访问文件流,按只读方式
  136.             randomFile = new RandomAccessFile(fileName, "r");
  137.             // 文件长度,字节数
  138.             long fileLength = randomFile.length();
  139.             // 读文件的起始位置
  140.             int beginIndex = (fileLength > 4? 4 : 0;
  141.             // 将读文件的开始位置移到beginIndex位置。
  142.             randomFile.seek(beginIndex);
  143.             byte[] bytes = new byte[10];
  144.             int byteread = 0;
  145.             // 一次读10个字节,如果文件内容不足10个字节,则读剩下的字节。
  146.             // 将一次读取的字节数赋给byteread
  147.             while ((byteread = randomFile.read(bytes)) != -1) {
  148.                 System.out.write(bytes, 0, byteread);
  149.             }
  150.         } catch (IOException e) {
  151.             e.printStackTrace();
  152.         } finally {
  153.             if (randomFile != null) {
  154.                 try {
  155.                     randomFile.close();
  156.                 } catch (IOException e1) {
  157.                 }
  158.             }
  159.         }
  160.     }

  161.     /**
  162.      * 显示输入流中还剩的字节数
  163.      */
  164.     private static void showAvailableBytes(InputStream in) {
  165.         try {
  166.             System.out.println("当前字节输入流中的字节数为:" + in.available());
  167.         } catch (IOException e) {
  168.             e.printStackTrace();
  169.         }
  170.     }

  171.     public static void main(String[] args) {
  172.         String fileName = "C:/temp/newTemp.txt";
  173.         ReadFromFile.readFileByBytes(fileName);
  174.         ReadFromFile.readFileByChars(fileName);
  175.         ReadFromFile.readFileByLines(fileName);
  176.         ReadFromFile.readFileByRandomAccess(fileName);
  177.     }
  178. }

  179. 5、将内容追加到文件尾部
  180. public class AppendToFile {
  181.     /**
  182.      * A方法追加文件:使用RandomAccessFile
  183.      */
  184.     public static void appendMethodA(String fileName, String content) {
  185.         try {
  186.             // 打开一个随机访问文件流,按读写方式
  187.             RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw");
  188.             // 文件长度,字节数
  189.             long fileLength = randomFile.length();
  190.             //将写文件指针移到文件尾。
  191.             randomFile.seek(fileLength);
  192.             randomFile.writeBytes(content);
  193.             randomFile.close();
  194.         } catch (IOException e) {
  195.             e.printStackTrace();
  196.         }
  197.     }

  198.     /**
  199.      * B方法追加文件:使用FileWriter
  200.      */
  201.     public static void appendMethodB(String fileName, String content) {
  202.         try {
  203.             //打开一个写文件器,构造函数中的第二个参数true表示以追加形式写文件
  204.             FileWriter writer = new FileWriter(fileName, true);
  205.             writer.write(content);
  206.             writer.close();
  207.         } catch (IOException e) {
  208.             e.printStackTrace();
  209.         }
  210.     }

  211.     public static void main(String[] args) {
  212.         String fileName = "C:/temp/newTemp.txt";
  213.         String content = "new append!";
  214.         //按方法A追加文件
  215.         AppendToFile.appendMethodA(fileName, content);
  216.         AppendToFile.appendMethodA(fileName, "append end. \n");
  217.         //显示文件内容
  218.         ReadFromFile.readFileByLines(fileName);
  219.         //按方法B追加文件
  220.         AppendToFile.appendMethodB(fileName, content);
  221.         AppendToFile.appendMethodB(fileName, "append end. \n");
  222.         //显示文件内容
  223.         ReadFromFile.readFileByLines(fileName);
  224.     }
  225. }