本程序实现了遍历文件夹及其子文件夹下所有的txt文件,将这些文件整合成一个文件,然后将该文件又拆分成大小为50k的文本文件,名称分别为1.txt,2.txt,3.txt。。。。。。
由于对IO不是很熟,此程序耗费了我很长的时间。在编写程序的过程中遇到了很多问题,比如文本乱码,如何遍历,如何判断文件格式,又如何正确读取和写入文件内容,如何等分文件等等等等,现在程序可以基本实现以上功能,但仍有一个bug,就是每次拆分完后的最后一个文件存在丢失字符的问题,虽然丢失的不多,但仍是一个很严重的bug,由于时间关系,本人以后再研究该bug。现在先将已经能运行的成果分享出来。
import java.io.*; public class TextUnion { public static void main(String[] args) { new TextUnion().bianli(new File("C:/test2"));//遍历C盘下的test2文件夹下的所有txt文件并合并 //hebing(new File("C:/a.txt")); File f = new File("C:/kenny.txt"); chaifen(f);//拆分合并后的文件 } public void bianli(File f) { File[] file = f.listFiles(); for(int i=0;i<file.length;i++) { if(file[i].isDirectory()) { bianli(file[i]); } else { if(file[i].getName().endsWith(".txt")) System.out.println(file[i].getName()); hebing(file[i]); } } } public static void hebing(File f) { try { InputStreamReader fr = new InputStreamReader(new FileInputStream(f),"GB2312"); BufferedReader br = new BufferedReader(fr); String filepath = "C:/kenny.txt"; File ff = new File(filepath); FileWriter fw = new FileWriter(ff,true); //OutputStreamWriter fw = new OutputStreamWriter(ffw,"GB2312"); BufferedWriter bw = new BufferedWriter(fw); String str; while((str = br.readLine())!=null) { //System.out.println("xiedongxi"); bw.append(str+"/r/n"); } bw.close(); br.close(); } catch (Exception e) { e.printStackTrace(); } //return ff; } public static void chaifen(File f) { try { //String path = null; RandomAccessFile rf = new RandomAccessFile(f,"r"); long len = rf.length(); long start = rf.getFilePointer(); System.out.println(start); System.out.println(len); int num = 1; while(start<len) { String path = "C:/"+ num + ".txt"; System.out.println(path); File ff = new File(path); byte[] buf = new byte[512]; int lent = 0; FileOutputStream fw = new FileOutputStream(ff); rf.seek(start); while(true) { lent = rf.read(buf); String str = new String(buf,"UTF-8"); fw.write(str.getBytes()); fw.flush(); if(ff.length()>50*1024) { num ++; start = rf.getFilePointer(); System.out.println(start); fw.close(); break; } } } rf.close(); } catch (Exception e) { e.printStackTrace(); } } }
由于该问题的解决方法在网上不容易找到,所以大部分算法都是本人想出来的,没有考虑效率的问题(能想出来对我来说已经是很大的挑战了),编写的有些粗糙,易读性不强,有望高人多多指教!
另外加一点小常识:
如何查看操作系统字符集,在Windows平台下,直接在命令行中,输入:chcp
可以得到操作系统的代码页信息,你可以从控制面板的语言选项中,可以查看代码页对应的详细的字符集信息。
405

被折叠的 条评论
为什么被折叠?



