我有一个 input.txt
文件,假设有 520 行。
我必须用 java 编写一个代码,它会像这样。
从前 200 行创建名为 file-001.txt
的第一个文件。然后从 201-400 行创建另一个 file-002
。然后 file-003.txt
来自剩余的行。
我已经编写了这个代码,它只写了前 200 行。为了将其工作更新为上述场景,我需要进行哪些更改。
public class DataMaker {
public static void main(String args[]) throws IOException{
DataMaker dm=new DataMaker();
String file= "D:\\input.txt";
int roll=1;
String rollnum ="file-00"+roll;
String outputfilename="D:\\output\\"+rollnum+".txt";
String urduwords;
String path;
ArrayList<String> where = new ArrayList<String>();
int temp=0;
try(BufferedReader br = new BufferedReader(new FileReader(file))) {
for(String line; (line = br.readLine()) != null; ) {
++temp;
if(temp<201){ //may be i need some changes here
dm.filewriter(line+" "+temp+")",outputfilename);
}
}
} catch (FileNotFoundException e) {
System.out.println("File not found");
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
void filewriter(String linetoline,String filename) throws IOException{
BufferedWriter fbw =null;
try{
OutputStreamWriter writer = new OutputStreamWriter(
new FileOutputStream(filename, true), "UTF-8");
fbw = new BufferedWriter(writer);
fbw.write(linetoline);
fbw.newLine();
}catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
finally {
fbw.close();
}
}
}
一种方法可以使用 if else
但我不能只使用它,因为我的实际文件有 6000 多行。
我希望这段代码像我运行代码一样工作,并给我 30 多个输出文件。
最佳答案
您可以更改以下位:
if(temp<201){ //may be i need some changes here
dm.filewriter(line+" "+temp+")",outputfilename);
}
为此:
dm.filewriter(line, "D:\\output\\file-00" + ((temp/200)+1) + ".txt");
这将确保前 200 行转到第一个文件,接下来的 200 行转到下一个文件,依此类推。
此外,您可能希望将 200 行批处理在一起并一次性写入它们,而不是每次都创建一个 writer
并写入文件。
关于java - 在java中从一个文本文件创建多个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43472168/