[Java] java读写文件操作 →→→→→进入此内容的聊天室

来自 , 2021-01-13, 写在 Java, 查看 214 次.
URL http://www.code666.cn/view/92977ae4
  1. package test;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.File;
  5. import java.io.FileInputStream;
  6. import java.io.FileOutputStream;
  7. import java.io.InputStreamReader;
  8. import java.util.regex.Matcher;
  9. import java.util.regex.Pattern;
  10.  
  11. public class ReadTxtUtils {
  12.  
  13.     /**
  14.      * @param args
  15.      */
  16.     public static void main(String[] args) {
  17.         String regEx = "['   ']+"; // 一个或多个空格
  18.  
  19.         Pattern p = Pattern.compile(regEx);
  20.  
  21.         try {
  22.             String encoding = "UTF8"; // 字符编码(可解决中文乱码问题 )
  23.             File file = new File("d:/jinzhou.txt");
  24.             if (file.isFile() && file.exists()) {
  25.                 InputStreamReader read = new InputStreamReader(new FileInputStream(file), encoding);
  26.                 BufferedReader bufferedReader = new BufferedReader(read);
  27.  
  28.                 FileOutputStream out = null;  
  29.  
  30.                 out = new FileOutputStream(new File("D:/jinzhou1.txt"));
  31.  
  32.                 String lineTXT = null;
  33.                 int count = -1;
  34.                 while ((lineTXT = bufferedReader.readLine()) != null) {
  35.                     count += 1;
  36.                     Matcher m = p.matcher(lineTXT);
  37.                     String str = count + "," + m.replaceAll(",").trim();
  38.                     System.out.println(str.substring(0, str.length() - 1));
  39.                     out.write(str.substring(0, str.length() - 1).getBytes());  
  40.                 }
  41.                 read.close();
  42.                 out.close();
  43.             } else {
  44.                 System.out.println("找不到指定的文件!");
  45.             }
  46.         } catch (Exception e) {
  47.             System.out.println("读取文件内容操作出错");
  48.             e.printStackTrace();
  49.         }
  50.     }
  51.  
  52. }
  53.  
  54.  

回复 " java读写文件操作"

这儿你可以回复上面这条便签

captcha