Java 读写文件 字符分隔

前一段时间因为需要帮别人写了简单的字符串分隔的java小程序,尽管最后没用上,但是作为练习还是不错的。

需求:对于像如下的字符创将其分隔为两列,这样就可以直接粘贴的Excel中各自列,否则一个一个分隔会耗费很多时间。

16 bit microcomputer 16 位微型计算机
3 d distribution 三维分布
4 bit slice processor 4位片处理机
5 reference 5伏基准电压源
a d converter 模拟数字转换器模数转换器
abbreviated code 缓冲存储器
abbreviated dialing 快速呼叫
aberration 象差
abnormal glow discharge 异常辉光放电
abnormal reflections 异常反射
abrasion 磨耗
abrasive 磨料
abrasive dust 磨粉
abrasive jet machining 磨料喷射加工
abrasive jet trimming 磨料喷射蝶
abrasive paste 磨蚀剂
abrasive trimming 研磨蝶

基本思路:按行读取文件,对于每行的字符串从后面找第一个空格,因为汉字一般是连在一起的(对以个别的有数字的暂时不管,分解完成后在手工做这些少数的问题)。从后面的第一个空格分开,将两个子字符串各自写入单独的文件。

代码如下:import java.io.*; public class MainHT { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub if (args.length == 1) { MainHT mainHT = new MainHT(); mainHT.ReadFile(args[0]); } else{ System.out.println("Usage fileName"); } } public void ReadFile(String fileNameandPath) { String record = null; int recCount = 0; try { FileReader fr = new FileReader(fileNameandPath); BufferedReader br = new BufferedReader(fr); record = new String(); FileWriter fw1 = new FileWriter("one.txt"); PrintWriter pw1= new PrintWriter(fw1); FileWriter fw2 = new FileWriter("two.txt"); PrintWriter pw2= new PrintWriter(fw2); while ((record = br.readLine()) != null) { recCount++; System.out.println(recCount + ": " + record); String str = record; int index = str.lastIndexOf(" "); String str1 = str.substring(0,index); String str2 = str.substring(index, str.length() ); pw1.println(str1 ) ; pw2.println(str2 ) ; } br.close(); fr.close(); fw1.close(); pw1.close(); fw2.close(); pw2.close(); } catch (IOException e) { System.out.println("Uh oh, got an IOException error!"); e.printStackTrace(); } } public void CreateOneFile(FileWriter fw, PrintWriter out) { try { fw = new FileWriter("one.txt"); out = new PrintWriter(fw); out.println("Create one file "); } catch (IOException e) { System.out.println("Uh oh, got an IOException error!"); e.printStackTrace(); } } public void CreateTwoFile(FileWriter fw, PrintWriter out) { String record = null; int recCount = 0; try { fw = new FileWriter("one.txt"); out = new PrintWriter(fw); out.println("Create two file "); } catch (IOException e) { System.out.println("Uh oh, got an IOException error!"); e.printStackTrace(); } } }


javac MainHT

java MainHT danciFile.txt

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值