将文本文件拆分为相同大小的文件,而不会破坏JAVA中的单词

时间:2016-11-17 09:28:01

标签: java file split word-count

我的标题非常具体:我试图将txt文件拆分成多个具有相同大小的文件。 我设法使用这个功能:

public static int fileSplitting(String fichier, String dossSortie, int nbMachines) throws FileNotFoundException, IOException{
        int i=1;

        File f = new File(fichier);
        //FileReader fr = new FileReader(f);
        //BufferedReader br = new BufferedReader(fr);
        int sizeOfFiles =  (int) (f.length()/(nbMachines));

        System.out.print(sizeOfFiles);
        byte[] buffer = new byte[sizeOfFiles];

        try (BufferedInputStream bis = new BufferedInputStream(
                new FileInputStream(f))){
            int tmp = 0;
            while ((tmp = bis.read(buffer)) > 0) {
                //write each chunk of data into separate file with different number in name
                File newFile = new File(dossSortie+"S"+i);
                try (FileOutputStream out = new FileOutputStream(newFile)) {
                    out.write(buffer, 0, tmp);//tmp is chunk size
                    }
                i++;
            }
        }

        return i;
}

问题在于,当我需要保留每个单词时,此功能会切断单词。 例如,如果我有一个txt文件"我住在阿姆斯特丹",该功能会将它拆分为:"我住在Ams"," terdam"。 我想要这样的事情:"我住在","阿姆斯特丹"。

全部谢谢!

1 个答案:

答案 0 :(得分:0)

我无法完成这项工作,但我将文件拆分成一个单词数组,然后将我的文件分成具有相同字数的文件...... 这不完全是我想要做的事情,而且它不是一个美丽的方式"要做到这一点,但它并没有那么糟糕。