-1

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,

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:

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

2 回答 2

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.

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

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:

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

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

于 2013-08-14T19:36:03.077 回答
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:

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:

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

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

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.

于 2013-08-14T19:41:54.387 回答