Click here to Skip to main content
14,733,541 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a java program which reads a log file and displays the file in the console. Before displaying it should remove the timestamp. Therefore I implemented the following function,

public void readLogFile() {
		try {

			InputStream fis = new FileInputStream("C:\\Users\\manujayap.DIRECT\\eclipse-workspace-java\\LogRead\\src\\LogRead\\SocketLog.log");
			InputStreamReader isr = new InputStreamReader(fis);
			BufferedReader br = new BufferedReader(isr);
			String line;
			//loop through logFile
			while((line = br.readLine()) != null) {
				//passing the new line

		} catch (IOException e) {
			// TODO Auto-generated catch block


In here
is a seperate function which insert the line into an array list.

When I compile the program it throws an exception.

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -3
	at java.base/java.lang.String.substring(
	at LogRead.DataImpl.readLogFile(
	at LogRead.DataMain.main(

How can I solve this issue? Thank you!

What I have tried:

I tried giving start and endpoint to substring
Updated 16-Feb-20 22:52pm

The substring method does not modify the original string; instead, it returns a new string. Thus, the line
does not do anything. You probably want to write
line = line.substring(3);
instead, which allows to save the new string back into the original one.

But, the issue here seems to be that 3 is not a valid index into the string. You may want to test for the length before trying to truncate:
if (line.length() > 3)
   { line = line.substring(3); }

Java - String substring() Method example[^]
At a guess - and we don't have your data, so we can't tell - the error message implies that the string does not have 4 characters in it. Since you are in a loop, that implies that at least one line in your file is too short - and there could be more, but most likely culprits are the first and last lines of the file.

So use the debugger, and look at exactly what is going on. Put a breakpoint on the first line in the function, and run your code through the debugger. Then look at your code, and at your data and work out what should happen manually. Then single step each line checking that what you expected to happen is exactly what did. When it isn't, that's when you have a problem, and you can back-track (or run it again and look more closely) to find out why.

Sorry, but we can't do that for you - time for you to learn a new (and very, very useful) skill: debugging!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900