Java读取文件内容和写入内容到文件

雨点打透心脏的1/2处 2022-06-07 04:06 441阅读 0赞

Java读取文件内容方法和写入内容到文件方法

  1. /**
  2. * One.txt中的数据如下:
  3. * 1
  4. * 2
  5. * 3
  6. * 4
  7. * 5
  8. * -----------------
  9. * 读操作方法
  10. */
  11. @Test
  12. public void readFileToList2() {
  13. File file = new File("C:\\Users\\Desktop\\One.txt");
  14. System.out.println("文件绝对路径 :"+file.getAbsolutePath());
  15. List<String> listStr = new ArrayList<String>();
  16. BufferedReader br = null;
  17. String str = null;
  18. try {
  19. br = new BufferedReader(new FileReader(file));
  20. while ((str = br.readLine())!= null) {
  21. listStr.add(str);
  22. }
  23. } catch (FileNotFoundException e) {
  24. e.printStackTrace();
  25. }catch (IOException e) {
  26. e.printStackTrace();
  27. }
  28. System.out.println(listStr);
  29. writeListToFile(listStr);// 调用写操作方法
  30. }
  31. /**
  32. * 实现写操作方法
  33. */
  34. private void writeListToFile(List<String> listStr) {
  35. File file = new File("C:\\Users\\Desktop\\Azzan.txt");// 要写入的文件路径
  36. if (!file.exists()) {// 判断文件是否存在
  37. try {
  38. file.createNewFile();// 如果文件不存在创建文件
  39. System.out.println("文件"+file.getName()+"不存在已为您创建!");
  40. } catch (IOException e) {
  41. System.out.println("创建文件异常!");
  42. e.printStackTrace();
  43. }
  44. } else {
  45. System.out.println("文件"+file.getName()+"已存在!");
  46. }
  47. for (String str : listStr) {// 遍历listStr集合
  48. FileOutputStream fos = null;
  49. PrintStream ps = null;
  50. try {
  51. fos = new FileOutputStream(file,true);// 文件输出流 追加
  52. ps = new PrintStream(fos);
  53. } catch (FileNotFoundException e) {
  54. e.printStackTrace();
  55. }
  56. String string = str + "\r\n";// +换行
  57. ps.print(string); // 执行写操作
  58. ps.close(); // 关闭流
  59. }
  60. System.out.println("文件写入完毕!");
  61. }

发表评论

表情:
评论列表 (有 0 条评论,441人围观)

还没有评论,来说两句吧...

相关阅读