使用JAVA按2个字段对文件中的行进行排序

时间:2012-09-10 16:48:31

标签: java sorting

我在一家印刷公司工作,这家公司有许多COBOL程序,我的任务是 将COBOL程序转换为JAVA程序。我在一次转换中遇到了麻烦。我需要获取一个文件,每行都是一条记录,每行都阻止数据。

一行的例子是

60000003448595072410013 FFFFFFFFFFV 80     0001438001000014530020120808060134

我需要按照19-23个字符的5位数字排序数据,然后按行中的第一个字符排序。

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());
    }
}

这是我到目前为止所做的,我不确定从哪里开始,或者即使这是正确的方法 去分类文件。文件排序后,它将存储到另一个文件中并进行处理 再次使用另一个程序准备打印。

3 个答案:

答案 0 :(得分: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

这款手机的自动更正错误了我的回答

答案 1 :(得分:1)

将文件读入ArrayList(而不是数组)。使用以下方法:

// 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());

然后,使用自定义Comparator对其进行排序:

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个数字或哪个数字;我已将它们留作你填写的功能)。 最后,将其写入输出文件:

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

(根据需要添加导入和try / catch)

答案 2 :(得分:0)

此代码将根据大型机排序参数对文件进行排序。

您将3个参数传递给main类的Sort方法。

  1. 输入文件路径。
  2. 输出文件路径。
  3. 大型机排序格式中的排序参数。在您的情况下,此字符串将为19,5,CH,A,1,1,CH,A
  4. 第一个类SortParameter类包含排序参数的实例。 sort参数字符串中的每组4个参数都有一个实例。除了getDifference方法之外,此类是基本的getter / setter类。 getDifference方法将一些排序比较器代码带入SortParameter类,以简化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();
            }
        }
    
    }