1
關於此代碼: 基本上我正在編寫一個程序,將給定的大文本文件分割成更小的「n」個大小爲10 MB的文件。爲什麼我無法在我的文件分割程序(Java)中達到正確的解決方案?
工作流的代碼:
- 打開源文件時,發現存在於文件中的行號。
- 計算一個行的近似大小(字節)和每個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);
}
}
輸出: 邏輯的作品,正被創建的小文件數量,但全部的分割文件包含第一分割文件的數據。
謝謝您閱讀到現在。我希望有人能給我一個解決方案。