java创建txt文件并存入内容

川长思鸟来 2022-06-17 05:30 260阅读 0赞
  1. import java.io.BufferedReader;
  2. import java.io.File;
  3. import java.io.FileInputStream;
  4. import java.io.FileOutputStream;
  5. import java.io.IOException;
  6. import java.io.InputStreamReader;
  7. import java.io.PrintWriter;
  8. public class txtExport {
  9. private static String path = "D:/";
  10. private static String filenameTemp;
  11. public static void main(String[] args) throws IOException {
  12. txtExport.creatTxtFile("你好");
  13. txtExport.writeTxtFile("你好");
  14. }
  15. /**
  16. * 创建文件
  17. *
  18. * @throws IOException
  19. */
  20. public static boolean creatTxtFile(String name) throws IOException {
  21. boolean flag = false;
  22. filenameTemp = path + name + ".txt";
  23. File filename = new File(filenameTemp);
  24. if (!filename.exists()) {
  25. filename.createNewFile();
  26. flag = true;
  27. }
  28. return flag;
  29. }
  30. /**
  31. * 写文件
  32. *
  33. * @param newStr
  34. * 新内容
  35. * @throws IOException
  36. */
  37. public static boolean writeTxtFile(String newStr) throws IOException {
  38. // 先读取原有文件内容,然后进行写入操作
  39. boolean flag = false;
  40. String filein = newStr + "\r\n";
  41. String temp = "";
  42. FileInputStream fis = null;
  43. InputStreamReader isr = null;
  44. BufferedReader br = null;
  45. FileOutputStream fos = null;
  46. PrintWriter pw = null;
  47. try {
  48. // 文件路径
  49. File file = new File(filenameTemp);
  50. // 将文件读入输入流
  51. fis = new FileInputStream(file);
  52. isr = new InputStreamReader(fis);
  53. br = new BufferedReader(isr);
  54. StringBuffer buf = new StringBuffer();
  55. // 保存该文件原有的内容
  56. for (int j = 1; (temp = br.readLine()) != null; j++) {
  57. buf = buf.append(temp);
  58. // System.getProperty("line.separator")
  59. // 行与行之间的分隔符 相当于“\n”
  60. buf = buf.append(System.getProperty("line.separator"));
  61. }
  62. buf.append(filein);
  63. fos = new FileOutputStream(file);
  64. pw = new PrintWriter(fos);
  65. pw.write(buf.toString().toCharArray());
  66. pw.flush();
  67. flag = true;
  68. } catch (IOException e1) {
  69. // TODO 自动生成 catch 块
  70. throw e1;
  71. } finally {
  72. if (pw != null) {
  73. pw.close();
  74. }
  75. if (fos != null) {
  76. fos.close();
  77. }
  78. if (br != null) {
  79. br.close();
  80. }
  81. if (isr != null) {
  82. isr.close();
  83. }
  84. if (fis != null) {
  85. fis.close();
  86. }
  87. }
  88. return flag;
  89. }
  90. }

发表评论

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

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

相关阅读

    相关 Java写入txt文件内容

    Java写入数据进txt文件,需求:多条数据追加进文件,且需要处理`中文编码`问题。 > 以下代码只能处理向文件添加数据的功能,但是会覆盖掉之前的数据 import