Java读取文件方法大全

来源:互联网 发布:cf开挂软件 编辑:程序博客网 时间:2024/05/17 23:01

一、

java读写txt文件总结1

1、按字节读取文件内容

2、按字符读取文件内容
3、按行读取文件内容

4、随机读取文件内容 

[java] view plaincopy
  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.      */  
  47.     public static void readFileByChars(String fileName) {  
  48.         File file = new File(fileName);  
  49.         Reader reader = null;  
  50.         try {  
  51.             System.out.println("以字符为单位读取文件内容,一次读一个字节:");  
  52.             // 一次读一个字符  
  53.             reader = new InputStreamReader(new FileInputStream(file));  
  54.             int tempchar;  
  55.             while ((tempchar = reader.read()) != -1) {  
  56.                 // 对于windows下,\r\n这两个字符在一起时,表示一个换行。  
  57.                 // 但如果这两个字符分开显示时,会换两次行。  
  58.                 // 因此,屏蔽掉\r,或者屏蔽\n。否则,将会多出很多空行。  
  59.                 if (((char) tempchar) != '\r') {  
  60.                     System.out.print((char) tempchar);  
  61.                 }  
  62.             }  
  63.             reader.close();  
  64.         } catch (Exception e) {  
  65.             e.printStackTrace();  
  66.         }  
  67.         try {  
  68.             System.out.println("以字符为单位读取文件内容,一次读多个字节:");  
  69.             // 一次读多个字符  
  70.             char[] tempchars = new char[30];  
  71.             int charread = 0;  
  72.             reader = new InputStreamReader(new FileInputStream(fileName));  
  73.             // 读入多个字符到字符数组中,charread为一次读取字符数  
  74.             while ((charread = reader.read(tempchars)) != -1) {  
  75.                 // 同样屏蔽掉\r不显示  
  76.                 if ((charread == tempchars.length)  
  77.                         && (tempchars[tempchars.length - 1] != '\r')) {  
  78.                     System.out.print(tempchars);  
  79.                 } else {  
  80.                     for (int i = 0; i < charread; i++) {  
  81.                         if (tempchars[i] == '\r') {  
  82.                             continue;  
  83.                         } else {  
  84.                             System.out.print(tempchars[i]);  
  85.                         }  
  86.                     }  
  87.                 }  
  88.             }  
  89.   
  90.         } catch (Exception e1) {  
  91.             e1.printStackTrace();  
  92.         } finally {  
  93.             if (reader != null) {  
  94.                 try {  
  95.                     reader.close();  
  96.                 } catch (IOException e1) {  
  97.                 }  
  98.             }  
  99.         }  
  100.     }  
  101.   
  102.     /** 
  103.      * 以行为单位读取文件,常用于读面向行的格式化文件 
  104.      */  
  105.     public static void readFileByLines(String fileName) {  
  106.         File file = new File(fileName);  
  107.         BufferedReader reader = null;  
  108.         try {  
  109.             System.out.println("以行为单位读取文件内容,一次读一整行:");  
  110.             reader = new BufferedReader(new FileReader(file));  
  111.             String tempString = null;  
  112.             int line = 1;  
  113.             // 一次读入一行,直到读入null为文件结束  
  114.             while ((tempString = reader.readLine()) != null) {  
  115.                 // 显示行号  
  116.                 System.out.println("line " + line + ": " + tempString);  
  117.                 line++;  
  118.             }  
  119.             reader.close();  
  120.         } catch (IOException e) {  
  121.             e.printStackTrace();  
  122.         } finally {  
  123.             if (reader != null) {  
  124.                 try {  
  125.                     reader.close();  
  126.                 } catch (IOException e1) {  
  127.                 }  
  128.             }  
  129.         }  
  130.     }  
  131.   
  132.     /** 
  133.      * 随机读取文件内容 
  134.      */  
  135.     public static void readFileByRandomAccess(String fileName) {  
  136.         RandomAccessFile randomFile = null;  
  137.         try {  
  138.             System.out.println("随机读取一段文件内容:");  
  139.             // 打开一个随机访问文件流,按只读方式  
  140.             randomFile = new RandomAccessFile(fileName, "r");  
  141.             // 文件长度,字节数  
  142.             long fileLength = randomFile.length();  
  143.             // 读文件的起始位置  
  144.             int beginIndex = (fileLength > 4) ? 4 : 0;  
  145.             // 将读文件的开始位置移到beginIndex位置。  
  146.             randomFile.seek(beginIndex);  
  147.             byte[] bytes = new byte[10];  
  148.             int byteread = 0;  
  149.             // 一次读10个字节,如果文件内容不足10个字节,则读剩下的字节。  
  150.             // 将一次读取的字节数赋给byteread  
  151.             while ((byteread = randomFile.read(bytes)) != -1) {  
  152.                 System.out.write(bytes, 0, byteread);  
  153.             }  
  154.         } catch (IOException e) {  
  155.             e.printStackTrace();  
  156.         } finally {  
  157.             if (randomFile != null) {  
  158.                 try {  
  159.                     randomFile.close();  
  160.                 } catch (IOException e1) {  
  161.                 }  
  162.             }  
  163.         }  
  164.     }  
  165.   
  166.     /** 
  167.      * 显示输入流中还剩的字节数 
  168.      */  
  169.     private static void showAvailableBytes(InputStream in) {  
  170.         try {  
  171.             System.out.println("当前字节输入流中的字节数为:" + in.available());  
  172.         } catch (IOException e) {  
  173.             e.printStackTrace();  
  174.         }  
  175.     }  
  176.   
  177.     public static void main(String[] args) {  
  178.         String fileName = "C:/temp/newTemp.txt";  
  179.         ReadFromFile.readFileByBytes(fileName);  
  180.         ReadFromFile.readFileByChars(fileName);  
  181.         ReadFromFile.readFileByLines(fileName);  
  182.         ReadFromFile.readFileByRandomAccess(fileName);  
  183.     }  
  184. }  
  185.   
  186. 5、将内容追加到文件尾部  
  187. public class AppendToFile {  
  188.     /** 
  189.      * A方法追加文件:使用RandomAccessFile 
  190.      */  
  191.     public static void appendMethodA(String fileName, String content) {  
  192.         try {  
  193.             // 打开一个随机访问文件流,按读写方式  
  194.             RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw");  
  195.             // 文件长度,字节数  
  196.             long fileLength = randomFile.length();  
  197.             //将写文件指针移到文件尾。  
  198.             randomFile.seek(fileLength);  
  199.             randomFile.writeBytes(content);  
  200.             randomFile.close();  
  201.         } catch (IOException e) {  
  202.             e.printStackTrace();  
  203.         }  
  204.     }  
  205.   
  206.     /** 
  207.      * B方法追加文件:使用FileWriter 
  208.      */  
  209.     public static void appendMethodB(String fileName, String content) {  
  210.         try {  
  211.             //打开一个写文件器,构造函数中的第二个参数true表示以追加形式写文件  
  212.             FileWriter writer = new FileWriter(fileName, true);  
  213.             writer.write(content);  
  214.             writer.close();  
  215.         } catch (IOException e) {  
  216.             e.printStackTrace();  
  217.         }  
  218.     }  
  219.   
  220.     public static void main(String[] args) {  
  221.         String fileName = "C:/temp/newTemp.txt";  
  222.         String content = "new append!";  
  223.         //按方法A追加文件  
  224.         AppendToFile.appendMethodA(fileName, content);  
  225.         AppendToFile.appendMethodA(fileName, "append end. \n");  
  226.         //显示文件内容  
  227.         ReadFromFile.readFileByLines(fileName);  
  228.         //按方法B追加文件  
  229.         AppendToFile.appendMethodB(fileName, content);  
  230.         AppendToFile.appendMethodB(fileName, "append end. \n");  
  231.         //显示文件内容  
  232.         ReadFromFile.readFileByLines(fileName);  
  233.     }  
  234. }  

二、

java读写txt文件总结2

[java] view plaincopy
  1. import java.io.BufferedReader;  
  2. import java.io.File;  
  3. import java.io.FileReader;  
  4. import java.io.FileWriter;  
  5.   
  6. public class TxtFile {  
  7. public void read() {  
  8. FileReader fr = null;  
  9. BufferedReader br = null;  
  10. try {  
  11. fr = new FileReader("F://a.txt");  
  12. br = new BufferedReader(fr);  
  13. String line = br.readLine();  
  14. while (line != null) {  
  15. System.out.println(line);  
  16. line = br.readLine();  
  17. }  
  18. catch (Exception e) {  
  19. System.out.println(e);  
  20. finally {  
  21. try {  
  22. if (br != null)  
  23. br.close();  
  24. if (fr != null)  
  25. fr.close();// 关闭文件  
  26. catch (Exception e) {  
  27. System.out.println(e);  
  28. }  
  29. }  
  30. }  
  31.   
  32. public void write() {  
  33. File file = null;  
  34. FileWriter fw = null;  
  35. try {  
  36. file = new File("F://a.txt");  
  37. fw = new FileWriter(file);  
  38. for (int i = 0; i < 20; i++) {  
  39. fw.append("第" + i + 1 + "次");  
  40. }  
  41. catch (Exception e) {  
  42. System.out.println(e);  
  43. finally {  
  44. try {  
  45. if (fw != null)  
  46. fw.close();// 关闭文件  
  47. catch (Exception e) {  
  48. System.out.println(e);  
  49. }  
  50. }  
  51. }  
  52. }  

三、

Java文件读写总结3各方法效率测试

读文件:

FileInputStream
通过打开一个到实际文件的连接来创建一个 FileInputStream,该文件通过文件系统中的路径名

name 指定。创建一个新 FileDescriptor 对象来表示此文件连接。
InputStreamReader
InputStreamReader 是字节流通向字符流的桥梁:它使用指定的 charset 读取字节并将其解码为字

符。它使用的字符集可以由名称指定或显式给定,否则可能接受平台默认的字符集。
BufferedReader
从字符输入流中读取文本,缓冲各个字符,从而提供字符、数组和行的高效读取。 可以指定缓冲区

的大小,或者可使用默认的大小。大多数情况下,默认值就足够大了。
StringBuffer
线程安全的可变字符序列。一个类似于 String 的字符串缓冲区,但不能修改。虽然在任意时间点上

它都包含某种特定的字符序列,但通过某些方法调用可以改变该序列的长度和内容。

[java] view plaincopy
  1. public static void main(String[] args) {  
  2.   
  3.  //读取文件内容  
  4.             File a = new File("C:/add2.txt");  
  5.             if(a.exists()){  
  6.              FileInputStream fi = new FileInputStream(a);  
  7.              InputStreamReader isr = new InputStreamReader(fi, "GBk");  
  8.              BufferedReader bfin = new BufferedReader(isr);  
  9.              String rLine = "";  
  10.              while((rLine = bfin.readLine())!=null){  
  11.               System.out.println(rLine);  
  12.              }  
  13.             }  
  14.   
  15. }  


写文件:

 在java写文件中,通常会使用FileOutputStream和FileWriter,FileWriter只能写文本文件。FileOutputStream也经常结合BufferedOutputStream。因为实际应用中写文本文件的情况占了大多数。所以下面测试用不同的方式生成一个相同行数、大小相同的文件的三种不同方式。
   

[java] view plaincopy
  1. import java.io.File;  
  2. import java.io.FileOutputStream;  
  3. import java.io.*;  
  4.   
  5. public class FileTest {  
  6.     publicFileTest() {  
  7.     }  
  8.   
  9.     publicstatic void main(String[] args) {  
  10.        FileOutputStream out = null;  
  11.        FileOutputStream outSTr = null;  
  12.        BufferedOutputStream Buff=null;  
  13.        FileWriter fw = null;  
  14.        int count=1000;//写文件行数  
  15.        try {  
  16.            out = new FileOutputStream(new File("C:/add.txt"));  
  17.            long begin = System.currentTimeMillis();  
  18.            for (int i = 0; i < count; i++) {  
  19.                out.write("测试java 文件操作\r\n".getBytes());  
  20.            }  
  21.            out.close();  
  22.            long end = System.currentTimeMillis();  
  23.            System.out.println("FileOutputStream执行耗时:" + (end - begin) + "豪秒");  
  24.   
  25.            outSTr = new FileOutputStream(new File("C:/add0.txt"));  
  26.             Buff=new BufferedOutputStream(outSTr);  
  27.            long begin0 = System.currentTimeMillis();  
  28.            for (int i = 0; i < count; i++) {  
  29.                Buff.write("测试java 文件操作\r\n".getBytes());  
  30.            }  
  31.            Buff.flush();  
  32.            Buff.close();  
  33.            long end0 = System.currentTimeMillis();  
  34.            System.out.println("BufferedOutputStream执行耗时:" + (end0 - begin0) +" 豪秒");  
  35.   
  36.   
  37.            fw = new FileWriter("C:/add2.txt");  
  38.            long begin3 = System.currentTimeMillis();  
  39.            for (int i = 0; i < count; i++) {  
  40.                fw.write("测试java 文件操作\r\n");  
  41.            }  
  42.                        fw.close();  
  43.            long end3 = System.currentTimeMillis();  
  44.            System.out.println("FileWriter执行耗时:" + (end3 - begin3) + "豪秒");  
  45.   
  46.        } catch (Exception e) {  
  47.            e.printStackTrace();  
  48.        }  
  49.        finally {  
  50.            try {  
  51.                fw.close();  
  52.                Buff.close();  
  53.                outSTr.close();  
  54.                out.close();  
  55.            } catch (Exception e) {  
  56.                e.printStackTrace();  
  57.            }  
  58.        }  
  59.     }  
  60.   
  61.   
  62. }     

以下结果经过多次执行,取常出现的数据,由于只是简单比较,不做详细统计。

1.当count=1000的,即写文件1000行的时候,写出的文件大小为18.5KB:
FileOutputStream执行耗时:46 豪秒
BufferedOutputStream执行耗时:31 豪秒
FileWriter执行耗时:15 豪秒


2.当count=10000的,即写文件10000行的时候,写出的文件大小为185KB:
FileOutputStream执行耗时:188 豪秒
BufferedOutputStream执行耗时:32 豪秒
FileWriter执行耗时:16 豪秒

 

3.当count=100000的,即写文件100000行的时候,写出的文件大小为1856KB:
FileOutputStream执行耗时:1266 豪秒
BufferedOutputStream执行耗时:125 豪秒
FileWriter执行耗时:93 豪秒

 

4.当count=1000000的,即写文件1000000行的时候,写出的文件大小为18555KB:
FileOutputStream执行耗时:12063 豪秒
BufferedOutputStream执行耗时:1484 豪秒
FileWriter执行耗时:969 豪秒


   由以上数据可以看到,如果不用缓冲流BufferedOutputStream,FileOutputStream写文件的鲁棒性是很不好的。当写1000000行的文件的时候,FileOutputStream比FileWriter要慢11094毫秒(11秒),BufferedOutputStream比FileWriter慢515毫秒。
   不要小看这几秒的时间。当操作的数据量很大的时候,这点性能的差距就会很大了。在通用数据迁移工具导出数据库2千万条记录生成sql脚本文件的时候,性能性能相差10分钟以上。


四、

Java创建文件夹及文件 


[java] view plaincopy
  1. package Test;  
  2.   
  3.   
  4.     import java.io.File;  
  5.     import java.io.IOException;  
  6.   
  7.     public class CreateFileTest {  
  8.     /** 
  9.     * 创建单个文件 
  10.     * @param destFileName 文件名 
  11.     * @return 创建成功返回true,否则返回false 
  12.     */  
  13.     public static boolean CreateFile(String destFileName) {  
  14.        File file = new File(destFileName);  
  15.          
  16.        if (file.exists()) {  
  17.         System.out.println("创建单个文件" + destFileName + "失败,目标文件已存在!");  
  18.         return false;  
  19.        }  
  20.          
  21.          
  22.        if (destFileName.endsWith(File.separator)) {  
  23.         System.out.println("创建单个文件" + destFileName + "失败,目标不能是目录!");  
  24.         return false;  
  25.        }  
  26.          
  27.        if (!file.getParentFile().exists()) {  
  28.         System.out.println("目标文件所在路径不存在,准备创建。。。");  
  29.         if (!file.getParentFile().mkdirs()) {  
  30.          
  31.         System.out.println("创建目录文件所在的目录失败!");  
  32.         return false;  
  33.         }  
  34.        }  
  35.          
  36.     // 创建目标文件  
  37.        try {  
  38.         if (file.createNewFile()) {  
  39.         System.out.println("创建单个文件" + destFileName + "成功!");  
  40.         return true;  
  41.         } else {  
  42.         System.out.println("创建单个文件" + destFileName + "失败!");  
  43.         return false;  
  44.         }  
  45.        } catch (IOException e) {  
  46.         e.printStackTrace();  
  47.         System.out.println("创建单个文件" + destFileName + "失败!");  
  48.         return false;  
  49.        }  
  50.     }  
  51.     /** 
  52.     * 创建目录 
  53.     * @param destDirName 目标目录名 
  54.     * @return 目录创建成功返回true,否则返回false 
  55.     */  
  56.     public static boolean createDir(String destDirName) {  
  57.        File dir = new File(destDirName);  
  58.        if(dir.exists()) {  
  59.         System.out.println("创建目录" + destDirName + "失败,目标目录已存在!");  
  60.         return false;  
  61.        }  
  62.        if(!destDirName.endsWith(File.separator))  
  63.         destDirName = destDirName + File.separator;  
  64.        // 创建单个目录  
  65.        if(dir.mkdirs()) {  
  66.         System.out.println("创建目录" + destDirName + "成功!");  
  67.         return true;  
  68.        } else {  
  69.         System.out.println("创建目录" + destDirName + "成功!");  
  70.         return false;  
  71.        }  
  72.     }  
  73.   
  74.     /** 
  75.     * 创建临时文件 
  76.     * @param prefix 临时文件的前缀 
  77.     * @param suffix 临时文件的后缀 
  78.     * @param dirName 临时文件所在的目录,如果输入null,则在用户的文档目录下创建临时文件 
  79.     * @return 临时文件创建成功返回抽象路径名的规范路径名字符串,否则返回null 
  80.     */  
  81.     public static String createTempFile(String prefix, String suffix, String dirName) {  
  82.        File tempFile = null;  
  83.        try{  
  84.         if(dirName == null) {  
  85.         // 在默认文件夹下创建临时文件  
  86.         tempFile = File.createTempFile(prefix, suffix);  
  87.         return tempFile.getCanonicalPath();  
  88.         }else {  
  89.         File dir = new File(dirName);  
  90.         // 如果临时文件所在目录不存在,首先创建  
  91.         if(!dir.exists()) {  
  92.         if(!CreateFileTest.createDir(dirName)){  
  93.         System.out.println("创建临时文件失败,不能创建临时文件所在目录!");  
  94.         return null;  
  95.         }  
  96.         }  
  97.         tempFile = File.createTempFile(prefix, suffix, dir);  
  98.         return tempFile.getCanonicalPath();  
  99.         }  
  100.          
  101.        } catch(IOException e) {  
  102.         e.printStackTrace();  
  103.         System.out.println("创建临时文件失败" + e.getMessage());  
  104.         return null;  
  105.        }  
  106.     }  
  107.     public static void main(String[] args) {  
  108.     // 创建目录  
  109.        String dirName = "d:/test/test0/test1";  
  110.        CreateFileTest.createDir(dirName);  
  111.        // 创建文件  
  112.        String fileName = dirName + "/test2/testFile.txt";  
  113.        CreateFileTest.CreateFile(fileName);  
  114.        // 创建临时文件  
  115.        String prefix = "temp";  
  116.        String suffix = ".txt";  
  117.        for(int i = 0; i < 10; i++) {  
  118.         System.out.println("创建了临时文件:" + CreateFileTest.createTempFile(prefix, suffix, dirName));  
  119.        }  
  120.     }  
  121.     }  
原创粉丝点击