0
我正在创建一个程序,旨在采取n拆分数量并将文件拆分为该数量的子文件。在我的SplitFile.java中,我正在读取一个文件,传递一个子字符串数组,以显示每个拆分文件应该执行的文本。然后,我将字符串转换为一个字节数组,并将字节数组写入分割文件,但是我创建的每个文件都只是输出只是略有不同。字节阵列没有打印到文件正确
SplitFile.java
import java.io.*;
import java.nio.charset.Charset;
import java.util.ArrayList;
public class SplitFile
{
int numberOfSplits = 1;
File file;
String[] parts = new String[5];
public SplitFile(File file,int numberOfSplits)
{
this.file = file;
this.numberOfSplits = numberOfSplits;
}
public void FileSplitter() throws IOException
{
FileInputStream fis = new FileInputStream(file);
String fileText = readFile();
if(numberOfSplits == 2)
{
int mid = fileText.length()/2;
parts[0] = fileText.substring(0, mid);
parts[1] = fileText.substring(mid);
}
else if(numberOfSplits == 3)
{
int third = fileText.length()/3;
int secondThird = third + third;
parts[0] = fileText.substring(0, third);
parts[1] = fileText.substring(third, secondThird);
parts[2] = fileText.substring(secondThird);
}
for(int i = 1; i <= numberOfSplits; i++)
{
BufferedInputStream bis = new BufferedInputStream(new fileInputStream(file));
FileOutputStream out;
String name = file.getName();
byte[] b = parts[i - 1].getBytes(Charset.forName("UTF-8"));
int temp = 0;
while((temp = bis.read(b)) > 0);
{
File newFile = new File(name + " " + i + ".txt");
newFile.createNewFile();
out = new FileOutputStream(newFile);
out.write(b, 0, temp); // Writes to the file
out.close();
temp = 0;
}
}
}
public String readFile() throws IOException
{
BufferedReader br = new BufferedReader(new FileReader(file));
try
{
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null)
{
sb.append(line);
sb.append("\n");
line = br.readLine();
}
return sb.toString();
}
finally
{
br.close();
}
}
}
如果我在第2传,因为我想,这是不对的,在中间分裂它的分裂适量,用文件1是上半年和文件2的存在下半部分,而是给这两个文件的文本文件的结尾。我的问题似乎是在这里:
while((temp = bis.read(b)) > 0);
{
File newFile = new File(name + " " + i + ".txt");
newFile.createNewFile();
out = new FileOutputStream(newFile);
out.write(b, 0, temp); // Writes to the file
out.close();
temp = 0;
}
我会在这里使用的示例文件是这样的文件:
MYFILE.TXT
ABCDEFGHIJKLMNOPQRSTUVWXYZ
它分成两个文件,如下所示:
MYFILE.TXT 1
nopqrstuvqxyz
MYFILE.TXT 2
opqrstuvqxyz
的问题是什么你知道吗?
感谢您的编辑,但哇...我试过的东西,我甚至没有考虑这两行是我的概率最大的罪魁祸首LEM。非常感谢您的帮助。 – Midge