簡體   English   中英

使用JAVA按2個字段對文件中的行進行排序

[英]Sorting lines in a file by 2 fields with JAVA

我在一家有很多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());
    }
}

這是我到目前為止所擁有的,並且我不確定從這里到哪里,即使這是對文件進行排序的正確方法,也不確定。 文件排序后,將被存儲到另一個文件中,並用另一個程序再次處理以准備打印。

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

手機的自動更正弄亂了我的答案

將文件讀取到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());

然后,使用自定義比較器對其進行排序:

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位數字還是5位;我將它們留作函數供您填寫)。 最后,將其寫入輸出文件:

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

(添加導入並根據需要嘗試/捕獲)

此代碼將根據大型機排序參數對文件進行排序。

您將3個參數傳遞給Sort類的main方法。

  1. 輸入文件路徑。
  2. 輸出文件路徑。
  3. 大型機排序格式的排序參數。 在您的情況下,此字符串將為19,5,CH,A,1,1,CH,A

第一個類SortParameter類保存排序參數的實例。 排序參數字符串中的每4個參數組都有一個實例。 此類是基本的getter / setter類,但getDifference方法除外。 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();
        }
    }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM