java多种方式读文件,追加文件内容,对文件的各种操作 绝地灬酷狼 2022-06-05 09:09 275阅读 0赞 **一、多种方式读文件内容:** 1、按字节读取文件内容 **\[java\]** [ view plain][view plain] [ copy][view plain] [ print][view plain] [?][view plain] 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. 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. \} import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.RandomAccessFile; import java.io.Reader; /** * 以字节为单位读取文件,常用于读二进制文件,如图片、声音、影像等文件。 * @param fileName 文件的名 */ public static void readFileByBytes(String fileName){ File file = new File(fileName); InputStream in = null; try { System.out.println("以字节为单位读取文件内容,一次读一个字节:"); // 一次读一个字节 in = new FileInputStream(file); int tempbyte; while((tempbyte=in.read()) != -1){ System.out.write(tempbyte); } in.close(); } catch (IOException e) { e.printStackTrace(); return; } try { System.out.println("以字节为单位读取文件内容,一次读多个字节:"); //一次读多个字节 byte[] tempbytes = new byte[100]; int byteread = 0; in = new FileInputStream(fileName); ReadFromFile.showAvailableBytes(in); //读入多个字节到字节数组中,byteread为一次读入的字节数 while ((byteread = in.read(tempbytes)) != -1){ System.out.write(tempbytes, 0, byteread); } } catch (Exception e1) { e1.printStackTrace(); } finally { if (in != null){ try { in.close(); } catch (IOException e1) { } } } } 2、按字符读取文件内容 **\[java\]** [ view plain][view plain] [ copy][view plain] [ print][view plain] [?][view plain] 1. /\*\* 2. \* 以字符为单位读取文件,常用于读文本,数字等类型的文件 3. \* @param fileName 文件名 4. \*/ 5. public static void readFileByChars(String fileName)\{ 6. File file = new File(fileName); 7. Reader reader = null; 8. try \{ 9. System.out.println("以字符为单位读取文件内容,一次读一个字节:"); 10. // 一次读一个字符 11. reader = new InputStreamReader(new FileInputStream(file)); 12. int tempchar; 13. while ((tempchar = reader.read()) != -1)\{ 14. //对于windows下,\\r\\n这两个字符在一起时,表示一个换行。 15. //但如果这两个字符分开显示时,会换两次行。 16. //因此,屏蔽掉\\r,或者屏蔽\\n。否则,将会多出很多空行。 17. if (((char)tempchar) != ''\\r'')\{ 18. System.out.print((char)tempchar); 19. \} 20. \} 21. reader.close(); 22. \} catch (Exception e) \{ 23. e.printStackTrace(); 24. \} 25. try \{ 26. System.out.println("以字符为单位读取文件内容,一次读多个字节:"); 27. //一次读多个字符 28. char\[\] tempchars = new char\[30\]; 29. int charread = 0; 30. reader = new InputStreamReader(new FileInputStream(fileName)); 31. //读入多个字符到字符数组中,charread为一次读取字符数 32. while ((charread = reader.read(tempchars))!=-1)\{ 33. //同样屏蔽掉\\r不显示 34. if ((charread == tempchars.length)&&(tempchars\[tempchars.length-1\] != ''\\r''))\{ 35. System.out.print(tempchars); 36. \}else\{ 37. for (int i=0; i<charread; i++)\{ 38. if(tempchars\[i\] == ''\\r'')\{ 39. continue; 40. \}else\{ 41. System.out.print(tempchars\[i\]); 42. \} 43. \} 44. \} 45. \} 46. 47. \} catch (Exception e1) \{ 48. e1.printStackTrace(); 49. \}finally \{ 50. if (reader != null)\{ 51. try \{ 52. reader.close(); 53. \} catch (IOException e1) \{ 54. \} 55. \} 56. \} 57. \} /** * 以字符为单位读取文件,常用于读文本,数字等类型的文件 * @param fileName 文件名 */ public static void readFileByChars(String fileName){ File file = new File(fileName); Reader reader = null; try { System.out.println("以字符为单位读取文件内容,一次读一个字节:"); // 一次读一个字符 reader = new InputStreamReader(new FileInputStream(file)); int tempchar; while ((tempchar = reader.read()) != -1){ //对于windows下,\r\n这两个字符在一起时,表示一个换行。 //但如果这两个字符分开显示时,会换两次行。 //因此,屏蔽掉\r,或者屏蔽\n。否则,将会多出很多空行。 if (((char)tempchar) != ''\r''){ System.out.print((char)tempchar); } } reader.close(); } catch (Exception e) { e.printStackTrace(); } try { System.out.println("以字符为单位读取文件内容,一次读多个字节:"); //一次读多个字符 char[] tempchars = new char[30]; int charread = 0; reader = new InputStreamReader(new FileInputStream(fileName)); //读入多个字符到字符数组中,charread为一次读取字符数 while ((charread = reader.read(tempchars))!=-1){ //同样屏蔽掉\r不显示 if ((charread == tempchars.length)&&(tempchars[tempchars.length-1] != ''\r'')){ System.out.print(tempchars); }else{ for (int i=0; i<charread; i++){ if(tempchars[i] == ''\r''){ continue; }else{ System.out.print(tempchars[i]); } } } } } catch (Exception e1) { e1.printStackTrace(); }finally { if (reader != null){ try { reader.close(); } catch (IOException e1) { } } } } 3、按行读取文件内容 **\[java\]** [ view plain][view plain] [ copy][view plain] [ print][view plain] [?][view plain] 1. /\*\* 2. \* 以行为单位读取文件,常用于读面向行的格式化文件 3. \* @param fileName 文件名 4. \*/ 5. public static void readFileByLines(String fileName)\{ 6. File file = new File(fileName); 7. BufferedReader reader = null; 8. try \{ 9. System.out.println("以行为单位读取文件内容,一次读一整行:"); 10. reader = new BufferedReader(new FileReader(file)); 11. String tempString = null; 12. int line = 1; 13. //一次读入一行,直到读入null为文件结束 14. while ((tempString = reader.readLine()) != null)\{ 15. //显示行号 16. System.out.println("line " + line + ": " + tempString); 17. line++; 18. \} 19. reader.close(); 20. \} catch (IOException e) \{ 21. e.printStackTrace(); 22. \} finally \{ 23. if (reader != null)\{ 24. try \{ 25. reader.close(); 26. \} catch (IOException e1) \{ 27. \} 28. \} 29. \} 30. \} /** * 以行为单位读取文件,常用于读面向行的格式化文件 * @param fileName 文件名 */ public static void readFileByLines(String fileName){ File file = new File(fileName); BufferedReader reader = null; try { System.out.println("以行为单位读取文件内容,一次读一整行:"); reader = new BufferedReader(new FileReader(file)); String tempString = null; int line = 1; //一次读入一行,直到读入null为文件结束 while ((tempString = reader.readLine()) != null){ //显示行号 System.out.println("line " + line + ": " + tempString); line++; } reader.close(); } catch (IOException e) { e.printStackTrace(); } finally { if (reader != null){ try { reader.close(); } catch (IOException e1) { } } } } 4、随机读取文件内容 **\[java\]** [ view plain][view plain] [ copy][view plain] [ print][view plain] [?][view plain] 1. /\*\* 2. \* 随机读取文件内容 3. \* @param fileName 文件名 4. \*/ 5. public static void readFileByRandomAccess(String fileName)\{ 6. RandomAccessFile randomFile = null; 7. try \{ 8. System.out.println("随机读取一段文件内容:"); 9. // 打开一个随机访问文件流,按只读方式 10. randomFile = new RandomAccessFile(fileName, "r"); 11. // 文件长度,字节数 12. long fileLength = randomFile.length(); 13. // 读文件的起始位置 14. int beginIndex = (fileLength > 4) ? 4 : 0; 15. //将读文件的开始位置移到beginIndex位置。 16. randomFile.seek(beginIndex); 17. byte\[\] bytes = new byte\[10\]; 18. int byteread = 0; 19. //一次读10个字节,如果文件内容不足10个字节,则读剩下的字节。 20. //将一次读取的字节数赋给byteread 21. while ((byteread = randomFile.read(bytes)) != -1)\{ 22. System.out.write(bytes, 0, byteread); 23. \} 24. \} catch (IOException e)\{ 25. e.printStackTrace(); 26. \} finally \{ 27. if (randomFile != null)\{ 28. try \{ 29. randomFile.close(); 30. \} catch (IOException e1) \{ 31. \} 32. \} 33. \} 34. \} /** * 随机读取文件内容 * @param fileName 文件名 */ public static void readFileByRandomAccess(String fileName){ RandomAccessFile randomFile = null; try { System.out.println("随机读取一段文件内容:"); // 打开一个随机访问文件流,按只读方式 randomFile = new RandomAccessFile(fileName, "r"); // 文件长度,字节数 long fileLength = randomFile.length(); // 读文件的起始位置 int beginIndex = (fileLength > 4) ? 4 : 0; //将读文件的开始位置移到beginIndex位置。 randomFile.seek(beginIndex); byte[] bytes = new byte[10]; int byteread = 0; //一次读10个字节,如果文件内容不足10个字节,则读剩下的字节。 //将一次读取的字节数赋给byteread while ((byteread = randomFile.read(bytes)) != -1){ System.out.write(bytes, 0, byteread); } } catch (IOException e){ e.printStackTrace(); } finally { if (randomFile != null){ try { randomFile.close(); } catch (IOException e1) { } } } } 5.显示输入流中还剩的字节数 **\[java\]** [ view plain][view plain] [ copy][view plain] [ print][view plain] [?][view plain] 1. /\*\* 2. \* 显示输入流中还剩的字节数 3. \* @param in 4. \*/ 5. private static void showAvailableBytes(InputStream in)\{ 6. try \{ 7. System.out.println("当前字节输入流中的字节数为:" + in.available()); 8. \} catch (IOException e) \{ 9. e.printStackTrace(); 10. \} 11. \} /** * 显示输入流中还剩的字节数 * @param in */ private static void showAvailableBytes(InputStream in){ try { System.out.println("当前字节输入流中的字节数为:" + in.available()); } catch (IOException e) { e.printStackTrace(); } } **二、将内容追加到文件尾部:** **\[java\]** [ view plain][view plain] [ copy][view plain] [ print][view plain] [?][view plain] 1. import java.io.FileWriter; 2. import java.io.IOException; 3. import java.io.RandomAccessFile; 4. 5. public class AppendToFile \{ 6. 7. /\*\* 8. \* A方法追加文件:使用RandomAccessFile 9. \* @param fileName 文件名 10. \* @param content 追加的内容 11. \*/ 12. public static void appendMethodA(String fileName, String content)\{ 13. try \{ 14. // 打开一个随机访问文件流,按读写方式 15. RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw"); 16. // 文件长度,字节数 17. long fileLength = randomFile.length(); 18. //将写文件指针移到文件尾。 19. randomFile.seek(fileLength); 20. randomFile.writeBytes(content); 21. randomFile.close(); 22. \} catch (IOException e)\{ 23. e.printStackTrace(); 24. \} 25. \} 26. 27. /\*\* 28. \* B方法追加文件:使用FileWriter 29. \* @param fileName 30. \* @param content 31. \*/ 32. public static void appendMethodB(String fileName, String content)\{ 33. try \{ 34. //打开一个写文件器,构造函数中的第二个参数true表示以追加形式写文件 35. FileWriter writer = new FileWriter(fileName, true); 36. writer.write(content); 37. writer.close(); 38. \} catch (IOException e) \{ 39. e.printStackTrace(); 40. \} 41. \} 42. 43. /\*\* 44. \* 测试程序 45. \*/ 46. public static void main(String\[\] args) \{ 47. String fileName = "C:/temp/newTemp.txt"; 48. String content = "new append!"; 49. //按方法A追加文件 50. AppendToFile.appendMethodA(fileName, content); 51. AppendToFile.appendMethodA(fileName, "append end. \\n"); 52. //显示文件内容 53. ReadFromFile.readFileByLines(fileName); 54. //按方法B追加文件 55. AppendToFile.appendMethodB(fileName, content); 56. AppendToFile.appendMethodB(fileName, "append end. \\n"); 57. //显示文件内容 58. ReadFromFile.readFileByLines(fileName); 59. \} import java.io.FileWriter; import java.io.IOException; import java.io.RandomAccessFile; public class AppendToFile { /** * A方法追加文件:使用RandomAccessFile * @param fileName 文件名 * @param content 追加的内容 */ public static void appendMethodA(String fileName, String content){ try { // 打开一个随机访问文件流,按读写方式 RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw"); // 文件长度,字节数 long fileLength = randomFile.length(); //将写文件指针移到文件尾。 randomFile.seek(fileLength); randomFile.writeBytes(content); randomFile.close(); } catch (IOException e){ e.printStackTrace(); } } /** * B方法追加文件:使用FileWriter * @param fileName * @param content */ public static void appendMethodB(String fileName, String content){ try { //打开一个写文件器,构造函数中的第二个参数true表示以追加形式写文件 FileWriter writer = new FileWriter(fileName, true); writer.write(content); writer.close(); } catch (IOException e) { e.printStackTrace(); } } /** * 测试程序 */ public static void main(String[] args) { String fileName = "C:/temp/newTemp.txt"; String content = "new append!"; //按方法A追加文件 AppendToFile.appendMethodA(fileName, content); AppendToFile.appendMethodA(fileName, "append end. \n"); //显示文件内容 ReadFromFile.readFileByLines(fileName); //按方法B追加文件 AppendToFile.appendMethodB(fileName, content); AppendToFile.appendMethodB(fileName, "append end. \n"); //显示文件内容 ReadFromFile.readFileByLines(fileName); } **三、文件的创建、删除、移动、复制等各种操作类:** **\[java\]** [ view plain][view plain] [ copy][view plain] [ print][view plain] [?][view plain] 1. /\*\* 2. \* 文件的各种操作 3. \*/ 4. public class FileOperate\{ 5. /\*\* 6. \* 新建目录 7. \*/ 8. public void newFolder(String folderPath) \{ 9. try \{ 10. String filePath = folderPath; 11. filePath = filePath.toString(); 12. File myFilePath = new File(filePath); 13. if(!myFilePath.exists()) \{ 14. myFilePath.mkdir(); 15. \} 16. System.out.println("新建目录操作 成功执行"); 17. \} catch(Exception e) \{ 18. System.out.println("新建目录操作出错"); 19. e.printStackTrace(); 20. \} 21. \} 22. 23. /\*\* 24. \* 新建文件 25. \*/ 26. public void newFile(String filePathAndName, String fileContent)\{ 27. try \{ 28. String filePath = filePathAndName; 29. filePath = filePath.toString(); 30. File myFilePath = new File(filePath); 31. if (!myFilePath.exists()) \{ 32. myFilePath.createNewFile(); 33. \} 34. FileWriter resultFile = new FileWriter(myFilePath); 35. PrintWriter myFile = new PrintWriter(resultFile); 36. String strContent = fileContent; 37. myFile.println(strContent); 38. resultFile.close(); 39. System.out.println("新建文件操作 成功执行"); 40. \} catch (Exception e) \{ 41. System.out.println("新建目录操作出错"); 42. e.printStackTrace(); 43. \} 44. \} 45. 46. /\*\* 47. \* 删除文件 48. \*/ 49. public void delFile(String filePathAndName) \{ 50. try \{ 51. String filePath = filePathAndName; 52. filePath = filePath.toString(); 53. File myDelFile = new File(filePath); 54. myDelFile.delete(); 55. System.out.println("删除文件操作 成功执行"); 56. \} catch (Exception e) \{ 57. System.out.println("删除文件操作出错"); 58. e.printStackTrace(); 59. \} 60. \} 61. 62. /\*\* 63. \* 删除文件夹 64. \*/ 65. public void delFolder(String folderPath) \{ 66. try \{ 67. delAllFile(folderPath); //删除完里面所有内容 68. String filePath = folderPath; 69. filePath = filePath.toString(); 70. File myFilePath = new File(filePath); 71. if(myFilePath.delete()) \{ //删除空文件夹 72. System.out.println("删除文件夹" + folderPath + "操作 成功执行"); 73. \} else \{ 74. System.out.println("删除文件夹" + folderPath + "操作 执行失败"); 75. \} 76. \} catch (Exception e) \{ 77. System.out.println("删除文件夹操作出错"); 78. e.printStackTrace(); 79. \} 80. \} 81. 82. /\*\* 83. \* 删除文件夹里面的所有文件 84. \*/ 85. public void delAllFile(String path) \{ 86. File file = new File(path); 87. if(!file.exists())\{ 88. return; 89. \} 90. 91. if(!file.isDirectory()) \{ 92. return; 93. \} 94. 95. String\[\] tempList = file.list(); 96. File temp = null; 97. for (int i = 0; i < tempList.length; i++)\{ 98. if(path.endsWith(File.separator)) \{ 99. temp = new File(path + tempList\[i\]); 100. \} else \{ 101. temp = new File(path + File.separator + tempList\[i\]); 102. \} 103. 104. if (temp.isFile()) \{ 105. temp.delete(); 106. \} 107. 108. if (temp.isDirectory()) \{ 109. //delAllFile(path+"/"+ tempList\[i\]);//先删除文件夹里面的文件 110. delFolder(path+ File.separatorChar + tempList\[i\]);//再删除空文件夹 111. \} 112. \} 113. System.out.println("删除文件操作 成功执行"); 114. \} 115. 116. /\*\* 117. \* 复制单个文件 118. \*/ 119. public void copyFile(String oldPath, String newPath) \{ 120. try \{ 121. int bytesum = 0; 122. int byteread = 0; 123. File oldfile = new File(oldPath); 124. if (oldfile.exists()) \{ 125. //文件存在时 126. InputStream inStream = new FileInputStream(oldPath); //读入原文件 127. FileOutputStream fs = new FileOutputStream(newPath); 128. byte\[\] buffer = new byte\[1444\]; 129. while ( (byteread = inStream.read(buffer)) != -1) \{ 130. bytesum += byteread; //字节数 文件大小 131. System.out.println(bytesum); 132. fs.write(buffer, 0, byteread); 133. \} 134. inStream.close(); 135. \} 136. System.out.println("删除文件夹操作 成功执行"); 137. \} catch (Exception e) \{ 138. System.out.println("复制单个文件操作出错"); 139. e.printStackTrace(); 140. \} 141. \} 142. 143. /\*\* 144. \* 复制整个文件夹内容 145. \*/ 146. public void copyFolder(String oldPath, String newPath) \{ 147. try \{ 148. (new File(newPath)).mkdirs(); //如果文件夹不存在 则建立新文件夹 149. File a=new File(oldPath); 150. String\[\] file=a.list(); 151. File temp=null; 152. for (int i = 0; i < file.length; i++) \{ 153. if(oldPath.endsWith(File.separator)) \{ 154. temp=new File(oldPath+file\[i\]); 155. \} else \{ 156. temp=new File(oldPath+File.separator+file\[i\]); 157. \} 158. 159. if(temp.isFile()) \{ 160. FileInputStream input = new FileInputStream(temp); 161. FileOutputStream output = new FileOutputStream(newPath + "/" + 162. (temp.getName()).toString()); 163. byte\[\] b = new byte\[1024 \* 5\]; 164. int len; 165. while ( (len = input.read(b)) != -1) \{ 166. output.write(b, 0, len); 167. \} 168. output.flush(); 169. output.close(); 170. input.close(); 171. \} if(temp.isDirectory()) \{ 172. //如果是子文件夹 173. copyFolder(oldPath+"/"\+file\[i\],newPath+"/"\+file\[i\]); 174. \} 175. \} 176. System.out.println("复制文件夹操作 成功执行"); 177. \} catch (Exception e) \{ 178. System.out.println("复制整个文件夹内容操作出错"); 179. e.printStackTrace(); 180. \} 181. \} 182. 183. /\*\* 184. \* 移动文件到指定目录 185. \*/ 186. public void moveFile(String oldPath, String newPath) \{ 187. copyFile(oldPath, newPath); 188. delFile(oldPath); 189. \} 190. \} 191. [view plain]: http://blog.csdn.net/wangbaochu/article/details/48545939#
还没有评论,来说两句吧...