关于代码: 基本上我正在编写一个程序,它将给定的巨大文本文件拆分为较小的“n”个大小为 10 MB 的文件。
代码工作流程:
- 打开源文件,查找文件中存在的行数。
- 计算每行的近似大小(字节)和每 10mb 文件的行数。
- 查找创建和创建它们所需的文件数。
- 然后将源文件中的粘贴复制到拆分文件中。
问题: 程序正确拆分为 n 个文件,但所有文件都有相同的数据。这是因为在我的程序完成第一个拆分文件后,对于第二个文件,阅读器会自动返回到原始源文件的第一行。因此,所有拆分文件都包含与第一个拆分文件相同的数据。
代码:
package filespliter;
import java.io.*;
public class FileSpliter {
public int filecount(FileReader f) throws IOException
{
BufferedReader buf=new BufferedReader(f);
int count=0;
while(buf.readLine()!=null)
{
count++;
}
buf.close();
return count;
}
public int split_value_generator(File f, int count)
{
double b=(f.length());
System.out.println((b/1024)+"kb");
double i=(b/count);
System.out.println(" No. of bytes per line :"+i);
int splitfactor = ((int)(((1024*1024)*10)/i));
System.out.println(splitfactor+" lines per file");
return splitfactor;
}
public static void filecreate(int index)
{
String no;
int i=1;
while(index!=0) //index will be number of files I need to create
{
no=Integer.toString(i);
String key = ("Split"+no);
key=("e:\\wipro\\splits\\Split"+no+".txt");
File file= new File(key);
index--;
i++;
}
i=1;
}
public static void filewrite(int nof,int nol_pf) throws IOException
{ //nof - no. of files || nol_pf - no. of lines per file
BufferedWriter bwrite;
String key;
int index=1;
while(index<=nof)
{
key="e:\\wipro\\splits\\Split"+index+".txt";
System.out.println(key);
bwrite=new BufferedWriter(new FileWriter(key));
writelines(bwrite,nol_pf);
index++;
iteration+=nolpf2;
}
//bwrite.flush();
// bwrite.close();
System.out.println("Finished !");
}
public static void writelines(BufferedWriter b, int nol_pf)throws IOException
{
String temp;
BufferedReader scan=new BufferedReader(new FileReader("E://wipro//CBDL.txt"));
while(nol_pf!=0)
{
temp=scan.readLine();
b.write(temp);
b.newLine();
nol_pf--;
}
}
public static void main(String[] args) throws FileNotFoundException, IOException {
String path="E://wipro//CBDL.txt";
File source=new File(path);
FileReader file=new FileReader(source);
FileSpliter obj=new FileSpliter();
int count=obj.filecount(file);
int no_of_lines_per_file = obj.split_value_generator(source, count);
int no_of_files=count/no_of_lines_per_file;
System.out.println("Need to create "+no_of_files+" files ");
filecreate(no_of_files);
file.close();
filewrite(no_of_files,no_of_lines_per_file);
}
}
输出: 逻辑有效,创建了 n 个较小的文件,但所有拆分文件都包含第一个拆分文件的数据。
感谢您阅读到现在。我希望有人能给我一个解决方案。