Java,尝试格式化数据,获取错误

时间:2021-06-08 16:26:24

I am trying to Format file, but I am getting error

我正在尝试格式化文件,但我收到错误

File Look like this:

文件看起来像这样:

H10288720130719000000600000000245000000355600156646E                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

200000001       001538                 M000                                                                                                                                                                      00000                                                                                                                                                                                                      1 0000        A5008390102730000153800717230080 901027300                                                                                           

200000002       001545                 M000                                                                                                                                                                      00000                                                                                                                                                                                                      1 0000        A5008390102730000154500730383135 901027300                                                                                           
200000356       576270          201302B 250A CHILDS WORLD LEARNING CENTER                 S                            1725        MCCALLIE                    AVE                 CHATTANOOGA                 TN37404S                            1200      N HOLTZCLAW                   AVE                 CHATTANOOGA                 TN37406-30190071200 N HOLTZCLAW AVE                                              1 0000        A0008390102730057627037404302425 901027300                                                                                           

200000357       635571          201306FW250AHLEMANN            JAMES                      P                            87          PO BOX                                          HIGH VIEW                   WV26808                                         TEMPORARILY AWAY                                                                           TEMPORARILY AWAY                                                  1 0000        A0008390102730063557126808008787 901027300                                                                                           

if (32,33) is 2 than write in file,

如果(32,33)是2而不是写入文件,

Here is my code:

这是我的代码:

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;


public class usps1 {

    /**
     * @param args
     */

    public static void delFileFromDir(String dirPath) {
        File dir = new File(dirPath);
        if (dir.listFiles() == null)
            return;
        for (File file : dir.listFiles()) {
            if (!file.isDirectory())
                file.delete();
        }
    }


    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub

        File folderout = new File("FileOut");
        File[] listOfFilesout = folderout.listFiles();

        String filesout;


        for (int iout = 0; iout < listOfFilesout.length; iout++) {
            if (listOfFilesout[iout].isFile()) {

                filesout = listOfFilesout[iout].getName();

                if(listOfFilesout != null) {

                    try {
                        File movefilesfromout = new File("FileOut\\" + filesout);
                        //File movefilesto = new File("archive\\letters\\" + movefilesfrom.getName());
                        if (movefilesfromout.renameTo(new File("FileOut\\Done\\" + movefilesfromout.getName()))) {
                        System.out.println("Moves files ======================================================================>" + movefilesfromout);


                        }
                    } catch (Exception e3) {
                        e3.printStackTrace();
                    }

                }

            }
        }


        BufferedReader br = null;
        BufferedWriter bfAll = null;

        String delimiter = "|";

        File folder = new File("FileIn");
        System.out.println(folder);
        File[] BFFile = folder.listFiles();
        System.out.println(BFFile);


        for (File file : BFFile) {

            br = new BufferedReader(new FileReader(file));


            String filename = file.getName();
            String[] fileInitialName = filename.split("\\.");

            String outFileAll = ("FileOut" + File.separator
                    + fileInitialName[0] + "_All.txt");
            File oldFileAll = new File("FileOutAll"
                    + File.separator + file.getName());
            oldFileAll.delete();
            bfAll = new BufferedWriter(new FileWriter(outFileAll));

            String line;
            line = br.readLine();
            System.out.println(line);
            int invoiceLine = 0;

            StringBuilder tempILlines = new StringBuilder();
            int aCountAll = 0;

            StringBuffer headerAll = new StringBuffer("Record Type ID" + delimiter +
                                                      "Sequence Number" + delimiter +
                                                      "Participant Code" + delimiter +
                                                      "Keyline" + delimiter +
                                                      "Move Effective Date" + delimiter +
                                                      "Move Type" + delimiter +
                                                      "Deliverability Code" + delimiter +
                                                      "USPS Site ID" + delimiter +
                                                      "COA Name" + delimiter +
                                                      "Old Address Type" + delimiter +
                                                      "Old Urbanization Name" + delimiter +
                                                      "Parsed Old Address" + delimiter +
                                                      "Old City" + delimiter +
                                                      "Old State" + delimiter +
                                                      "Old Zip" + delimiter +
                                                      "New Address Type" + delimiter +
                                                      "New Urbanization Name" + delimiter +
                                                      "Parsed New Address" + delimiter +
                                                      "New City" + delimiter +
                                                      "New State" + delimiter +
                                                      "New Zip" + delimiter +
                                                      "Label Format New Address" + delimiter +
                                                      "Filler" + delimiter +
                                                      "Postage Due" + delimiter +
                                                      "PMB Info" + delimiter +
                                                      "Class/Notification Type" + delimiter);

            bfAll.write(headerAll.toString());
            bfAll.newLine();

            String writeFile = "";
            int flagAll = 0;
            int recordcountOfAll = 0;

            while ((line = br.readLine()) != null) {

                String typechk = line.substring(32,33);

                if ((typechk.equals("2"))) {
                    writeFile = "All";
                } 

                if (writeFile.equals("All")) {

                    if ((aCountAll == 1)) {

                        bfAll.write(invoiceLine + delimiter);
                        bfAll.write(tempILlines.toString());
                        bfAll.newLine();

                        aCountAll = 0;
                        invoiceLine = 0;

                        tempILlines.delete(0, tempILlines.length());
                    }

                    flagAll = 1;
                    aCountAll = 1;

                    bfAll.write(line.substring(32, 37)
                            + delimiter);
                    invoiceLine++;
                }



                bfAll.write(invoiceLine + delimiter);
                bfAll.write(tempILlines.toString());
                bfAll.newLine();
                bfAll.flush();
                bfAll.close();

                if (flagAll == 0) {
                    File fl = new File(outFileAll);
                    fl.delete();
                } else {

                    File oldOutAll = new File(outFileAll);
                    File newOutAll = new File("FileOut"
                            + File.separator + fileInitialName[0]
                            + "_All-recordcount-" + recordcountOfAll + ".txt");

                    oldOutAll.renameTo(newOutAll);
                    oldOutAll.delete();
                }

            }
        }


    }

}

I am getting error:

我收到错误:

FileIn
[Ljava.io.File;@7ffe01
H10288720130719000000600000000245000000355600156646E                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 33
    at java.lang.String.substring(Unknown Source)
    at usps1.main(usps1.java:135)

I don't know, why I am getting error, Please help me!! Thanks!!

我不知道,为什么我收到错误,请帮帮我!谢谢!!

This is line 135:

这是第135行:

String typechk = line.substring(32,33);

2 个解决方案

#1


1  

It looks like you're reading every line and calling substring(32,33) on it - for any line that isn't at least 33 characters long, these indices are out of bounds of the string (they don't exist). You need to check the length of the strings you're looking at before calling substring(). You can do this by calling line.legnth(), which will return the number of characters in the line.

看起来你正在读取每一行并在其上调用substring(32,33) - 对于任何长度不超过33个字符的行,这些索引超出了字符串的范围(它们不存在)。在调用substring()之前,您需要检查您正在查看的字符串的长度。您可以通过调用line.legnth()来执行此操作,该行将返回行中的字符数。

Note that you need to check the length before every call to substring(), not just the one I pointed out.

请注意,您需要在每次调用substring()之前检查长度,而不仅仅是我指出的那个。

If you want to skip lines that don't have enough characters for your substrings, you could put the following at the very beginning of your while loop:

如果你想跳过你的子串没有足够字符的行,你可以在while循环的最开头放置以下内容:

if (line.length() < 37) continue;

This will skip the rest of the body of the loop and move on to the next line.

这将跳过循环体的其余部分并继续到下一行。

#2


1  

In general, it is is bad practice to hard-code "magic numbers" like 32 and 33, especially when doing substring operations. If you expect the last character of each line to have a number in it (but the length of the line is potentially variable), try something like the following:

一般来说,硬编码“魔术数字”(如32和33)是不好的做法,尤其是在进行子串操作时。如果您希望每行的最后一个字符都有一个数字(但该行的长度可能是可变的),请尝试以下操作:

String typechk = line.substring(line.length() - 1);

If the lines in your file are all expected to be of uniform length, make sure to check against the length of the line before attempting to substring it. This way you can throw more useful errors that you can handle wherever you access this code.

如果文件中的行都预期长度均匀,请确保在尝试对其进行子串之前检查行的长度。这样,您可以抛出更多有用的错误,无论您在何处访问此代码,都可以处理这些错误。

EDIT: I had missed the file you posted at the top of your post. Before doing your substring(32, 33), do the following:

编辑:我错过了您在帖子顶部发布的文件。在执行子字符串(32,33)之前,请执行以下操作:

if (line.length > 37) {
    //your code here
}

I chose 37 since you have another substring(32, 37) later in your code.

我选择了37,因为你的代码后面有另一个子串(32,37)。

However, as I mentioned at the beginning of my post: magic numbers are BAD. Even if the numbers are constant, assign them to some private static final variable that is descriptive, like IMPORTANT_INDEX. Giving your numbers a name increases code readability and eases the pain of changing the numbers at any point down the line.

但是,正如我在帖子开头提到的那样:魔术数字是不好的。即使数字是常量,也可以将它们分配给一些描述性的私有静态最终变量,如IMPORTANT_INDEX。为您的号码命名可以提高代码的可读性,并减轻在任何时候更改数字的痛苦。

#1


1  

It looks like you're reading every line and calling substring(32,33) on it - for any line that isn't at least 33 characters long, these indices are out of bounds of the string (they don't exist). You need to check the length of the strings you're looking at before calling substring(). You can do this by calling line.legnth(), which will return the number of characters in the line.

看起来你正在读取每一行并在其上调用substring(32,33) - 对于任何长度不超过33个字符的行,这些索引超出了字符串的范围(它们不存在)。在调用substring()之前,您需要检查您正在查看的字符串的长度。您可以通过调用line.legnth()来执行此操作,该行将返回行中的字符数。

Note that you need to check the length before every call to substring(), not just the one I pointed out.

请注意,您需要在每次调用substring()之前检查长度,而不仅仅是我指出的那个。

If you want to skip lines that don't have enough characters for your substrings, you could put the following at the very beginning of your while loop:

如果你想跳过你的子串没有足够字符的行,你可以在while循环的最开头放置以下内容:

if (line.length() < 37) continue;

This will skip the rest of the body of the loop and move on to the next line.

这将跳过循环体的其余部分并继续到下一行。

#2


1  

In general, it is is bad practice to hard-code "magic numbers" like 32 and 33, especially when doing substring operations. If you expect the last character of each line to have a number in it (but the length of the line is potentially variable), try something like the following:

一般来说,硬编码“魔术数字”(如32和33)是不好的做法,尤其是在进行子串操作时。如果您希望每行的最后一个字符都有一个数字(但该行的长度可能是可变的),请尝试以下操作:

String typechk = line.substring(line.length() - 1);

If the lines in your file are all expected to be of uniform length, make sure to check against the length of the line before attempting to substring it. This way you can throw more useful errors that you can handle wherever you access this code.

如果文件中的行都预期长度均匀,请确保在尝试对其进行子串之前检查行的长度。这样,您可以抛出更多有用的错误,无论您在何处访问此代码,都可以处理这些错误。

EDIT: I had missed the file you posted at the top of your post. Before doing your substring(32, 33), do the following:

编辑:我错过了您在帖子顶部发布的文件。在执行子字符串(32,33)之前,请执行以下操作:

if (line.length > 37) {
    //your code here
}

I chose 37 since you have another substring(32, 37) later in your code.

我选择了37,因为你的代码后面有另一个子串(32,37)。

However, as I mentioned at the beginning of my post: magic numbers are BAD. Even if the numbers are constant, assign them to some private static final variable that is descriptive, like IMPORTANT_INDEX. Giving your numbers a name increases code readability and eases the pain of changing the numbers at any point down the line.

但是,正如我在帖子开头提到的那样:魔术数字是不好的。即使数字是常量,也可以将它们分配给一些描述性的私有静态最终变量,如IMPORTANT_INDEX。为您的号码命名可以提高代码的可读性,并减轻在任何时候更改数字的痛苦。