【发布时间】:2017-09-14 07:01:05
【问题描述】:
我有一个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 多个输出文件。
【问题讨论】:
-
这里可能在正确的轨道上。而不是 modulus arithmatic。
标签: java filestream file-handling