Currently I’m working on a program that parses through a file and takes characters 34-40 out of each line and drops them into a table in a database, however each time I run into a line that is less than 34 characters long, my program spits this error out:
WARNING: General Error:String index out of range: 40
I’m still a novice at Java so a helping hand is desired. Here is a portion of my code:
try
{
fstream = new FileInputStream(filename);
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
PreparedStatement deleteFields = null;
String deleteTable = "DELETE FROM info WHERE VOLSER IS NOT NULL;";
deleteFields = conn.prepareStatement(deleteTable);
deleteFields.executeUpdate();
deleteFields.close();
logger.info(deleteTable);
PreparedStatement updateFields = null;
String[] qmarks = new String[linenumber];
//Adding data to the database
for(int i = 0; i < linenumber; i++)
{
String cust = in.readLine();
String subCust = cust.substring(34,40);
qmarks[i] = subCust;
String updateString = "REPLACE INTO info" + " (VOLSER) " + "VALUE ('" + (qmarks[i]) + "');";
logger.info(updateString);
try
{
updateFields = conn.prepareStatement(updateString);
updateFields.executeUpdate();
updateFields.close();
}
catch (SQLException e)
{
logger.warning("Error:" + e.getMessage());
}
}
This script would run daily so in order to purge yesterday’s data I have to DELETE all contents of the table and reinsert all values again. After deleting, it then starts to build an array of new contents. There are two ways I can approach this, and I’m looking for feedback from the community on which way is the best. One way is the way I’m doing to now and try to capture characters 34-40 which in the following example would yield A00000
TMSS0000N-02:00:30 Moving Volume A00000 to NEXT
The other way would be to skip all other lines and find only the lines that have “MOVING VOLUME” in them [the timestamp at the beginning of the line changes, so I’d figured this way would be more difficult].
Would a simple IF statement somewhere in the FOR loop stop the error? For example:
if (cust.length >= 34)
{
cust.substring(34,40);
}
else
{
cust.substring = "XXXXXX";
}
When you call
cust.substring(34,40);, you need to make sure thatcust.length >= 40or it will throw the exception you get. See the javadoc forpublic String substring(int beginIndex, int endIndex):