2016-11-17 78 views
0

我的标题足够具体:我试图将一个txt文件拆分为多个具有相同大小的文件。 我没做到这一点使用此功能:将文本文件分割成大小相同的文件,而不会在JAVA中打破文字

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”。 我想这样的事情:“我住在”,“阿姆斯特丹”。

谢谢大家!

+0

如果文件应该具有完全相同的大小,就像寻找最大公约数的问题一样:https://en.wikipedia.org/wiki/Greatest_common_divisor但是您需要为所有长度的文字找到它 –

+0

在“字节”的事情变得更加棘手。在'String'对象中读取你的文件。你可以比'byte'轻松玩'String'。 –

+0

如果你住在罗马呢? “我住在罗马”是否有效? – walen

回答

0

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

相关问题