在Java中,在不中断单词的情况下将文本文件拆分为大小相等的文件
我正在尝试将一个txt文件拆分为多个大小相同的文件。我使用此函数成功地做到了这一点:在Java中,在不中断单词的情况下将文本文件拆分为大小相等的文件,java,file,split,word-count,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 = n
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文件“I live in Amsterdam”,函数会像这样拆分它:“I live in Ams”,“terdam”。我想要像“我住在”、“阿姆斯特丹”这样的东西。我不能做这项工作,但我将我的文件拆分为一个单词数组,然后将我的文件拆分为具有相同单词数的文件。这并不完全是我想要做的,也不是一种“漂亮的方式”,但也没那么糟糕。如果文件大小完全相等,就像寻找最大公约数的问题:但是你需要在
字节
的帮助下,为所有长度的字找到它,事情会变得更困难。在String
对象中读取文件。你玩String
比玩byte
容易。如果你住在罗马呢?“我住在罗马”是否有效?