java中多种方式读文件

来源:互联网 发布:最优化计算方法课后题 编辑:程序博客网 时间:2024/05/16 17:24
一、多种方式读文件内容。 
1、按字节读取文件内容 
2、按字符读取文件内容 
3、按行读取文件内容 

4、随机读取文件内容 

[java] view plaincopyprint?
  1. import java.io.BufferedReader;   
  2. import java.io.File;   
  3. import java.io.FileInputStream;   
  4. import java.io.FileReader;   
  5. import java.io.IOException;   
  6. import java.io.InputStream;   
  7. import java.io.InputStreamReader;   
  8. import java.io.RandomAccessFile;   
  9. import java.io.Reader;   
  10. public class ReadFromFile {   
  11. /**  
  12. * 以字节为单位读取文件,常用于读二进制文件,如图片、声音、影像等文件。  
  13. * @param fileName 文件的名  
  14. */   
  15. public static void readFileByBytes(String fileName){   
  16. File file = new File(fileName);   
  17. InputStream in = null;   
  18. try {   
  19. System.out.println("以字节为单位读取文件内容,一次读一个字节:");   
  20. // 一次读一个字节   
  21. in = new FileInputStream(file);   
  22. int tempbyte;   
  23. while((tempbyte=in.read()) != -1){   
  24. System.out.write(tempbyte);   
  25. }   
  26. in.close();   
  27. catch (IOException e) {   
  28. e.printStackTrace();   
  29. return;   
  30. }   
  31. try {   
  32. System.out.println("以字节为单位读取文件内容,一次读多个字节:");   
  33. //一次读多个字节   
  34. byte[] tempbytes = new byte[100];   
  35. int byteread = 0;   
  36. in = new FileInputStream(fileName);   
  37. ReadFromFile.showAvailableBytes(in);   
  38. //读入多个字节到字节数组中,byteread为一次读入的字节数   
  39. while ((byteread = in.read(tempbytes)) != -1){   
  40. System.out.write(tempbytes, 0, byteread);   
  41. }   
  42. catch (Exception e1) {   
  43. e1.printStackTrace();   
  44. finally {   
  45. if (in != null){   
  46. try {   
  47. in.close();   
  48. catch (IOException e1) {   
  49. }   
  50. }   
  51. }   
  52. }   
  53. /**  
  54. * 以字符为单位读取文件,常用于读文本,数字等类型的文件  
  55. * @param fileName 文件名  
  56. */   
  57. public static void readFileByChars(String fileName){   
  58. File file = new File(fileName);   
  59. Reader reader = null;   
  60. try {   
  61. System.out.println("以字符为单位读取文件内容,一次读一个字节:");   
  62. // 一次读一个字符   
  63. reader = new InputStreamReader(new FileInputStream(file));   
  64. int tempchar;   
  65. while ((tempchar = reader.read()) != -1){   
  66. //对于windows下,rn这两个字符在一起时,表示一个换行。   
  67. //但如果这两个字符分开显示时,会换两次行。   
  68. //因此,屏蔽掉r,或者屏蔽n。否则,将会多出很多空行。   
  69. if (((char)tempchar) != 'r'){   
  70. System.out.print((char)tempchar);   
  71. }   
  72. }   
  73. reader.close();   
  74. catch (Exception e) {   
  75. e.printStackTrace();   
  76. }   
  77. try {   
  78. System.out.println("以字符为单位读取文件内容,一次读多个字节:");   
  79. //一次读多个字符   
  80. char[] tempchars = new char[30];   
  81. int charread = 0;   
  82. reader = new InputStreamReader(new FileInputStream(fileName));   
  83. //读入多个字符到字符数组中,charread为一次读取字符数   
  84. while ((charread = reader.read(tempchars))!=-1){   
  85. //同样屏蔽掉r不显示   
  86. if ((charread == tempchars.length)&&(tempchars[tempchars.length-1] != 'r')){   
  87. System.out.print(tempchars);   
  88. }else{   
  89. for (int i=0; i<charread; i++){   
  90. if(tempchars[i] == 'r'){   
  91. continue;   
  92. }else{   
  93. System.out.print(tempchars[i]);   
  94. }   
  95. }   
  96. }   
  97. }   
  98. catch (Exception e1) {   
  99. e1.printStackTrace();   
  100. }finally {   
  101. if (reader != null){   
  102. try {   
  103. reader.close();   
  104. catch (IOException e1) {   
  105. }   
  106. }   
  107. }   
  108. }   
  109. /**  
  110. * 以行为单位读取文件,常用于读面向行的格式化文件  
  111. * @param fileName 文件名  
  112. */   
  113. public static void readFileByLines(String fileName){   
  114. File file = new File(fileName);   
  115. BufferedReader reader = null;   
  116. try {   
  117. System.out.println("以行为单位读取文件内容,一次读一整行:");   
  118. reader = new BufferedReader(new FileReader(file));   
  119. String tempString = null;   
  120. int line = 1;   
  121. //一次读入一行,直到读入null为文件结束   
  122. while ((tempString = reader.readLine()) != null){   
  123. //显示行号   
  124. System.out.println("line " + line + ": " + tempString);   
  125. line++;   
  126. }   
  127. reader.close();   
  128. catch (IOException e) {   
  129. e.printStackTrace();   
  130. finally {   
  131. if (reader != null){   
  132. try {   
  133. reader.close();   
  134. catch (IOException e1) {   
  135. }   
  136. }   
  137. }   
  138. }   
  139. /**  
  140. * 随机读取文件内容  
  141. * @param fileName 文件名  
  142. */   
  143. public static void readFileByRandomAccess(String fileName){   
  144. RandomAccessFile randomFile = null;   
  145. try {   
  146. System.out.println("随机读取一段文件内容:");   
  147. // 打开一个随机访问文件流,按只读方式   
  148. randomFile = new RandomAccessFile(fileName, "r");   
  149. // 文件长度,字节数   
  150. long fileLength = randomFile.length();   
  151. // 读文件的起始位置   
  152. int beginIndex = (fileLength > 4) ? 4 : 0;   
  153. //将读文件的开始位置移到beginIndex位置。   
  154. randomFile.seek(beginIndex);   
  155. byte[] bytes = new byte[10];   
  156. int byteread = 0;   
  157. //一次读10个字节,如果文件内容不足10个字节,则读剩下的字节。   
  158. //将一次读取的字节数赋给byteread   
  159. while ((byteread = randomFile.read(bytes)) != -1){   
  160. System.out.write(bytes, 0, byteread);   
  161. }   
  162. catch (IOException e){   
  163. e.printStackTrace();   
  164. finally {   
  165. if (randomFile != null){   
  166. try {   
  167. randomFile.close();   
  168. catch (IOException e1) {   
  169. }   
  170. }   
  171. }   
  172. }   
二、将内容追加到文件尾部


[java] view plaincopyprint?
  1. import java.io.FileWriter;   
  2. import java.io.IOException;   
  3. import java.io.RandomAccessFile;   
  4. /**  
  5. * 显示输入流中还剩的字节数  
  6. * @param in  
  7. */   
  8. private static void showAvailableBytes(InputStream in){   
  9. try {   
  10. System.out.println("当前字节输入流中的字节数为:" + in.available());   
  11. catch (IOException e) {   
  12. e.printStackTrace();   
  13. }   
  14. }   
  15. public static void main(String[] args) {   
  16. String fileName = "C:/temp/newTemp.txt";   
  17. ReadFromFile.readFileByBytes(fileName);   
  18. ReadFromFile.readFileByChars(fileName);   
  19. ReadFromFile.readFileByLines(fileName);   
  20. ReadFromFile.readFileByRandomAccess(fileName);   
  21. }   
  22. }   
  23. /**  
  24. * 将内容追加到文件尾部  
  25. */   
  26. public class AppendToFile {   
  27. /**  
  28. * A方法追加文件:使用RandomAccessFile  
  29. * @param fileName 文件名  
  30. * @param content 追加的内容  
  31. */   
  32. public static void appendMethodA(String fileName,   
  33. String content){   
  34. try {   
  35. // 打开一个随机访问文件流,按读写方式   
  36. RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw");   
  37. // 文件长度,字节数   
  38. long fileLength = randomFile.length();   
  39. //将写文件指针移到文件尾。   
  40. randomFile.seek(fileLength);   
  41. randomFile.writeBytes(content);   
  42. randomFile.close();   
  43. catch (IOException e){   
  44. e.printStackTrace();   
  45. }   
  46. }   
  47. /**  
  48. * B方法追加文件:使用FileWriter  
  49. * @param fileName  
  50. * @param content  
  51. */   
  52. public static void appendMethodB(String fileName, String content){   
  53. try {   
  54. //打开一个写文件器,构造函数中的第二个参数true表示以追加形式写文件   
  55. FileWriter writer = new FileWriter(fileName, true);   
  56. writer.write(content);   
  57. writer.close();   
  58. catch (IOException e) {   
  59. e.printStackTrace();   
  60. }   
  61. }   
  62. public static void main(String[] args) {   
  63. String fileName = "C:/temp/newTemp.txt";   
  64. String content = "new append!";   
  65. //按方法A追加文件   
  66. AppendToFile.appendMethodA(fileName, content);   
  67. AppendToFile.appendMethodA(fileName, "append end. n");   
  68. //显示文件内容   
  69. ReadFromFile.readFileByLines(fileName);   
  70. //按方法B追加文件   
  71. AppendToFile.appendMethodB(fileName, content);   
  72. AppendToFile.appendMethodB(fileName, "append end. n");   
  73. //显示文件内容   
  74. ReadFromFile.readFileByLines(fileName);   
  75. }   
  76. }  

操作文件实例:

[java] view plaincopyprint?
  1. import java.io.BufferedReader;  
  2. import java.io.File;  
  3. import java.io.FileOutputStream;  
  4. import java.io.FileReader;  
  5. import java.io.FileWriter;  
  6. import java.io.IOException;  
  7. import java.io.OutputStreamWriter;  
  8. import java.io.PrintWriter;  
  9.   
  10.   
  11. public class operFile {  
  12.   
  13.     /** 
  14.      * @param args 
  15.      * @throws IOException  
  16.      */  
  17.     class data{  
  18.         int id;  
  19.         double x;  
  20.         double y;  
  21.         public data(int id, double x, double y) {  
  22.             super();  
  23.             this.id = id;  
  24.             this.x = x;  
  25.             this.y = y;  
  26.         }  
  27.         public int getId() {  
  28.             return id;  
  29.         }  
  30.         public void setId(int id) {  
  31.             this.id = id;  
  32.         }  
  33.         public double getX() {  
  34.             return x;  
  35.         }  
  36.         public void setX(double x) {  
  37.             this.x = x;  
  38.         }  
  39.         public double getY() {  
  40.             return y;  
  41.         }  
  42.         public void setY(double y) {  
  43.             this.y = y;  
  44.         }  
  45.     }  
  46.     public static data[] readFileByLines(String fileName){   
  47.         data[] o=new data[52];  
  48.         File file = new File(fileName);   
  49.         BufferedReader reader = null;   
  50.         operFile f=new operFile();  
  51.         try {   
  52.         System.out.println("以行为单位读取文件内容,一次读一整行:");   
  53.         reader = new BufferedReader(new FileReader(file));   
  54.         String tempString = null;   
  55.         int line = 1;   
  56.         //一次读入一行,直到读入null为文件结束   
  57.         while ((tempString = reader.readLine()) != null){   
  58.         //显示行号   
  59.     //  System.out.println("line " + line + ": " + tempString);   
  60.         if(line>1){  
  61.             String[] c=tempString.split(" ");  
  62.             int id=Integer.parseInt(c[0]);  
  63.             double x=Double.parseDouble(c[1]);  
  64.             double y=Double.parseDouble(c[2]);  
  65.             data d=f.new data(id, x, y);  
  66.             d.setId(id);  
  67.             d.setX(x);  
  68.             d.setY(y);  
  69.             o[line-1]=d;  
  70.         }  
  71.         line++;   
  72.         }   
  73.         reader.close();   
  74.         } catch (IOException e) {   
  75.         e.printStackTrace();   
  76.         } finally {   
  77.         if (reader != null){   
  78.         try {   
  79.         reader.close();   
  80.         } catch (IOException e1) {   
  81.         }   
  82.         }   
  83.         }  
  84.         return o;  
  85.         }   
  86.     public static void main(String[] args){  
  87.         String file=new String("SAN.txt");  
  88.         data[] o=readFileByLines(file);  
  89.         for(int i=1;i<o.length;i++){  
  90.             System.out.println(o[i].getId()+"  "+o[i].getX()+"  "+o[i].getY());  
  91.         }  
  92.           
  93.     }  
  94.   
  95. }  


0 0
原创粉丝点击