2012-09-10 4 views
0

나는 COBOL에 많은 프로그램이있는 인쇄 회사에서 일하고 있으며, 은 COBOL 프로그램을 JAVA 프로그램으로 변환하도록되어있다. 나는 한 번의 회심에서 방해물에 빠졌습니다. 각 줄이 레코드이고 각 줄마다 데이터가 차단된다는 파일을 가져와야합니다. 라인의JAVA를 사용하여 2 개의 필드로 파일 정렬하기

예 내가 행의 첫 문자로 다음 19 ~ 23 자에서 5 자리 숫자로 데이터를 정렬 할 필요가

60000003448595072410013 FFFFFFFFFFV 80  0001438001000014530020120808060134 

입니다.

BufferedReader input; 
BufferedWriter output; 

String[] sort, sorted, style, accountNumber, customerNumber; 
String holder; 

int lineCount; 

int lineCounter() { 

    int result = 0; 
    boolean eof = false; 

    try { 
     FileReader inputFile = new FileReader("C:\\Users\\cbook\\Desktop\\Chemical\\" 
      + "LB26529.fil"); 
     input = new BufferedReader(inputFile); 

     while (!eof) { 

      holder = input.readLine(); 
      if (holder == null) { 
       eof = true; 
      } else { 
       result++; 
      } 
     } 

    } catch (IOException e) { 
     System.out.println("Error - " + e.toString()); 
    } 

    return result; 
} 

chemSort(){ 
    lineCount = this.lineCounter(); 
    sort = new String[lineCount]; 
    sorted = new String[lineCount]; 
    style = new String[lineCount]; 
    accountNumber = new String[lineCount]; 
    customerNumber = new String[lineCount]; 

    try { 
     FileReader inputFile = new FileReader("C:\\Users\\cbook\\Desktop\\Chemical\\" 
      + "LB26529.fil"); 
     input = new BufferedReader(inputFile); 

     for (int i = 0; i < (lineCount + 1); i++) { 
      holder = input.readLine(); 
      if (holder != null) { 
      sort[i] = holder; 
      style[i] = sort[i].substring(0, 1); 
      customerNumber[i] = sort[i].substring(252, 257); 
      } 
     } 
     } catch (IOException e) { 
      System.out.println("Error - " + e.toString()); 
    } 
} 

이 내가 지금까지 가지고 있고이 파일을 정렬에 대해 갈 수있는 올바른 방법 경우 여기에 또는에서 갈 곳 정말 모르겠어요. 파일을 정렬 한 후에는 다른 파일에 저장되고 을 다시 인쇄 할 수 있도록 다른 프로그램으로 처리합니다.

+0

정렬 방법을 명확히 할 수 있습니까? –

+0

죄송합니다. 오름차순으로 5 자리 숫자 다음에 한 자리 숫자로 오름차순으로 정렬하십시오. – JcBook

+3

문자 범위를 보는 비교기를 작성할 수 없습니까? 비교는 동일합니까? 그렇다면 첫 번째 문자를 봅니다. (내가 정확하게 기준을 이해한다면.) –

답변

2
List<String> linesAsList = new ArrayList<String>(); 
String line=null; 
while(null!=(line=reader.readLine())) linesAsList.add(line); 

Collections.sort(linesAsList, new Comparator<String>() { 
    public int compare(String o1,String o2){ 
    return (o1.substring(18,23)+o1.substring(0,1)).compareTo(o2.substring(18,23)+o2.substring(0,1)); 
    }}); 

for (String line:linesAsList) System.out.println(line); // or whatever output stream you want 

이 전화의 자동 고침

+0

아마도 당신은 새로운 Comparator() {...}를 의미 했겠지만, 어쨌든 이것이 작동한다고 생각하지 않습니다. –

+0

당신이'Comparator '을 원한다는 것에 동의하지만, 기능면에서 어떤 문제도 보이지 않습니다. (스타일 - 와이즈, 그것은 매우 읽을 수 없습니다). –

+0

그것은 당신이 자동 교정이라고 불렀다. ... 내가 추측하는 전화에서 내 자신의 잘못 게시 ;-) –

1

는 (배열 대신) ArrayList에로 파일을 읽어 내 대답을 엉망입니다. 나는 함수로를 떠 났어요

Collections.sort(lines, new Comparator<String>() { 
    public int compare(String a, String b) { 
     String a5 = theFiveNumbersOf(a); 
     String b5 = theFiveNumbersOf(b); 
     int firstComparison = a5.compareTo(b5); 
     if (firstComparison != 0) { return firstComparison; } 
     String a1 = theDigitOf(a); 
     String b1 = theDigitOf(b); 
     return a1.compareTo(b1); 
    } 
}); 

(무엇 숫자 5 자리 또는 비교하려는 것을 명확하지 않다 : 종류는 사용자 정의 비교기를 사용하여, 다음

// to declare the arraylist 
ArrayList<String> lines = new ArrayList<String>(); 

// to add a new line to it (within your reading-lines loop) 
lines.add(input.readLine()); 

: 다음과 같은 방법을 사용하여 당신이 기입하기 위해).

BufferedWriter ow = new BufferedWriter(new FileOutputStream("filename.extension")); 
for (String line : lines) { 
    ow.println(line); 
} 
ow.close(); 

(추가 수입을하고 필요에 따라 try/catch를 사용)이 코드는 메인 프레임 정렬 매개 변수를 기반으로 파일을 정렬합니다

0

: 마지막으로, 출력 파일에 기록.

메서드에 3 개의 매개 변수를 전달하면 Sort 클래스입니다.

  1. 입력 파일 경로.
  2. 출력 파일 경로.
  3. 메인 프레임 정렬 형식의 정렬 매개 변수입니다. 귀하의 경우이 문자열은 19,5,CH,A,1,1,CH,A

이 클래스는 클래스는 정렬 매개 변수의 인스턴스를 보유합니다. 정렬 매개 변수 문자열에는 4 개의 매개 변수 그룹마다 하나의 인스턴스가 있습니다. 이 클래스는 getDifference 메서드를 제외하고 기본 getter/setter 클래스입니다. getDifference 메서드는 클래스에 정렬 비교 자 코드를 가져와 Sort 클래스의 비교 자 코드를 단순화합니다.

public class SortParameter { 

    protected int fieldStartByte; 
    protected int fieldLength; 
    protected String fieldType; 
    protected String sortDirection; 

    public SortParameter(int fieldStartByte, int fieldLength, String fieldType, 
      String sortDirection) { 
     this.fieldStartByte = fieldStartByte; 
     this.fieldLength = fieldLength; 
     this.fieldType = fieldType; 
     this.sortDirection = sortDirection; 
    } 

    public int getFieldStartPosition() { 
     return fieldStartByte - 1; 
    } 

    public int getFieldEndPosition() { 
     return getFieldStartPosition() + fieldLength; 
    } 

    public String getFieldType() { 
     return fieldType; 
    } 

    public String getSortDirection() { 
     return sortDirection; 
    } 

    public int getDifference(String a, String b) { 
     int difference = 0; 

     if (getFieldType().equals("CH")) { 
      String as = a.substring(getFieldStartPosition(), 
        getFieldEndPosition()); 
      String bs = b.substring(getFieldStartPosition(), 
        getFieldEndPosition()); 
      difference = as.compareTo(bs); 
      if (getSortDirection().equals("D")) { 
       difference = -difference; 
      } 
     } 

     return difference; 
    } 

} 

Sort 클래스는 입력 파일을 읽을 입력 파일을 정렬하고 출력 파일을 작성하는 코드가 포함되어 있습니다. 이 클래스는 아마도 더 많은 오류 검사를 사용할 수 있습니다.

import java.io.BufferedReader; 
import java.io.BufferedWriter; 
import java.io.FileNotFoundException; 
import java.io.FileReader; 
import java.io.FileWriter; 
import java.io.IOException; 
import java.util.ArrayList; 
import java.util.Collections; 
import java.util.Comparator; 
import java.util.List; 

public class Sort implements Runnable { 

    protected List<String> lines; 

    protected String inputFilePath; 
    protected String outputFilePath; 
    protected String sortParameters; 

    public Sort(String inputFilePath, String outputFilePath, 
      String sortParameters) { 
     this.inputFilePath = inputFilePath; 
     this.outputFilePath = outputFilePath; 
     this.sortParameters = sortParameters; 
    } 

    @Override 
    public void run() { 
     List<SortParameter> parameters = parseParameters(sortParameters); 
     lines = read(inputFilePath); 
     lines = sort(lines, parameters); 
     write(outputFilePath, lines); 
    } 

    protected List<SortParameter> parseParameters(String sortParameters) { 
     List<SortParameter> parameters = new ArrayList<SortParameter>(); 
     String[] field = sortParameters.split(","); 
     for (int i = 0; i < field.length; i += 4) { 
      SortParameter parameter = new SortParameter(
        Integer.parseInt(field[i]), Integer.parseInt(field[i + 1]), 
        field[i + 2], field[i + 3]); 
      parameters.add(parameter); 
     } 
     return parameters; 
    } 

    protected List<String> sort(List<String> lines, 
      final List<SortParameter> parameters) { 

     Collections.sort(lines, new Comparator<String>() { 
      @Override 
      public int compare(String a, String b) { 
       for (SortParameter parameter : parameters) { 
        int difference = parameter.getDifference(a, b); 
        if (difference != 0) { 
         return difference; 
        } 
       } 
       return 0; 
      } 
     }); 

     return lines; 
    } 

    protected List<String> read(String filePath) { 
     List<String> lines = new ArrayList<String>(); 
     BufferedReader reader = null; 
     try { 
      String line; 
      reader = new BufferedReader(new FileReader(filePath)); 
      while ((line = reader.readLine()) != null) { 
       lines.add(line); 
      } 
     } catch (FileNotFoundException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } finally { 
      try { 
       if (reader != null) { 
        reader.close(); 
       } 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
     return lines; 
    } 

    protected void write(String filePath, List<String> lines) { 
     BufferedWriter writer = null; 
     try { 
      writer = new BufferedWriter(new FileWriter(filePath)); 
      for (String line : lines) { 
       writer.write(line); 
       writer.newLine(); 
      } 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } finally { 
      try { 
       if (writer != null) { 
        writer.flush(); 
        writer.close(); 
       } 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
    } 

    public static void main(String[] args) { 
     if (args.length < 3) { 
      System.err.println("The sort process requires 3 parameters."); 
      System.err.println(" 1. The input file path."); 
      System.err.println(" 2. The output file path."); 
      System.err.print (" 3. The sort parameters in mainframe "); 
      System.err.println("sort format. Example: 15,5,CH,A"); 
     } else { 
      new Sort(args[0], args[1], args[2]).run(); 
     } 
    } 

} 
관련 문제