2017-04-18 5 views
3

나는 하나의 input.txt 파일을 가지고 있습니다.이 파일은 520 행이라고 가정합니다. 자바에서 코드를 만들어야합니다.자바의 한 텍스트 파일에서 여러 파일 만들기

처음 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); 
} 

:

+0

: 여기

은 예입니다. <201, 대신에 [modulus arithmatic]을보십시오 (http://stackoverflow.com/questions/90238/whats-the-syntax-for-mod-in-java). –

답변

1

다음과 같은 비트 변경할 수 있습니다

dm.filewriter(line, "D:\\output\\file-00" + ((temp/200)+1) + ".txt"); 

이 확실 처음 200 선이 첫 번째 파일로 이동하게됩니다, 다음에 200 개 선 등 다음 파일로 이동 .

또한, 매번 writer을 작성하고 파일에 쓰는 대신 200 줄을 함께 배치하여 한 번에 쓸 수 있습니다.

당신은 현재 FileWriter를 생성하는 방법이있을 수 있습니다
+0

방금 ​​파일에 기록 될 데이터를 변경했습니다. 출력 파일 이름과 아무 관련이 없습니다. 친절하게 다시 한번보세요. –

+0

@AdnanAli는 입력 해 주셔서 감사합니다. 답변을 업데이트했습니다. –

+0

어떻게 작동하는지 알려 드리겠습니다. 1083 행의 input.txt 파일을 제공했습니다. 코드는 각각 5 줄을 포함하는 200 개의 텍스트 파일을 만들었습니다. 그래서. 200x5 = 1000 및 83 줄이 방금 사라졌습니다. –

0

, false, 다음, 현재 FileWriter을 닫고, 라인 limit 수까지 읽고 그것을 읽을 수있을만큼이 있다면 true를 반환하는 경우는 할 수 없었다 제한 라인 수를 읽습니다 (즉, 다음 호출을 중단하고 더 많은 라인을 읽거나 다음 파일을 쓰지 마십시오).

다음은 Reader, 새 파일 이름 및 제한 번호를 전달하여 루프로 호출합니다. 여기에 오른쪽 궤도에 아마

import java.io.BufferedReader; 
import java.io.BufferedWriter; 
import java.io.FileNotFoundException; 
import java.io.FileOutputStream; 
import java.io.FileReader; 
import java.io.IOException; 
import java.io.OutputStreamWriter; 

public class DataMaker { 
    public static void main(final String args[]) throws IOException { 
     DataMaker dm = new DataMaker(); 
     String file = "D:\\input.txt"; 
     int roll = 1; 
     String rollnum = null; 
     String outputfilename = null; 

     boolean shouldContinue = false; 

     try (BufferedReader br = new BufferedReader(new FileReader(file))) { 

      do { 

       rollnum = "file-00" + roll; 
       outputfilename = "D:\\output\\" + rollnum + ".txt"; 
       shouldContinue = dm.fillFile(outputfilename, br, 200); 
       roll++; 
      } while (shouldContinue); 

     } catch (FileNotFoundException e) { 
      System.out.println("File not found"); 
      e.printStackTrace(); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 

    } 

    private boolean fillFile(final String outputfilename, final BufferedReader reader, final int limit) 
      throws IOException { 

     boolean result = false; 
     String line = null; 
     BufferedWriter fbw = null; 
     int temp = 0; 
     try { 
      OutputStreamWriter writer = new OutputStreamWriter(
        new FileOutputStream(outputfilename, true), "UTF-8"); 
      fbw = new BufferedWriter(writer); 

      while (temp < limit && ((line = reader.readLine()) != null)) { 

       temp++; 
       fbw.write(line); 
       fbw.newLine(); 

      } 

      // abort if we didn't manage to read the "limit" number of lines 
      result = (temp == limit); 

     } catch (Exception e) { 
      System.out.println("Error: " + e.getMessage()); 
     } finally { 
      fbw.close(); 
     } 

     return result; 

    } 

}