【问题标题】:Splitting a text file into equal size files without breaking words in Java [closed]将文本文件拆分为大小相等的文件而不破坏Java中的单词[关闭]
【发布时间】:2020-12-06 19:19:57
【问题描述】:

我正在尝试将一个 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”。我想要类似的内容:“我住在”、“阿姆斯特丹”。

【问题讨论】:

  • 如果文件应该具有完全相同的大小,例如寻找最大公约数的问题:en.wikipedia.org/wiki/Greatest_common_divisor 但您需要找到所有单词长度的文件
  • byte 的帮助下,事情变得更加艰难。在String 对象中读取您的文件。与byte 相比,您可以轻松地使用String
  • 如果你住在罗马呢? “我住在罗马”是否有效?

标签: java file split word-count


【解决方案1】:

我无法完成这项工作,但我将文件拆分为单词数组,然后将文件拆分为单词数相等的文件。这不完全是我想做的事,也不是一种“美丽的方式”,但也没有那么糟糕。

【讨论】:

    猜你喜欢
    • 2011-01-02
    • 1970-01-01
    • 1970-01-01
    • 2017-08-18
    • 2016-09-16
    • 2011-12-07
    • 1970-01-01
    • 2019-01-24
    • 2010-10-13
    相关资源
    最近更新 更多