-1

My .java file consists of a series of codes and each line is of variable size. The .java file is shown below:

public class MyC{
    public void MyMethod()
    {
        System.out.println("My method has been accessed");
        System.out.println("hi");
        String l;
        int x=0;
    }
}

Briefly, what i want to do is to scan the .java file for errors and capture the errors in a string. I have used a diagnostic collector to capture the start and end positions of the error.

Suppose I've made an error at line 7: in x=0; The diagnostic collector will return me the positions for example 143-145 error has occurred.

I also get the line numbers but the positions returned are relative to the whole .java file. Thus using the line numbers would be pointless as each line is of variable length and the positions are relative to the whole file. It will be difficult to compute the actual position of the error at a line.

And there is no way for me to get the end position of the last character in the previous line if there is no error at the last character of the previous line(e.g: error at line 7: previous line = line 6).

Is there a way for me to get a string by using its position(start and end) from a java file?

Daro Royoss
  • 25
  • 1
  • 4

1 Answers1

0

The easiest way is to use a RandomAccessFile.

It has a method called seek, which takes the position it should seek to:

String getStringFromFile(String fileName, long position, int length) throws IOException {
    byte[] buffer = new byte[length]; // You may want to take care of multi-byte encodings here
    RandomAccessFile file = new RandomAccessFile(fileName, "r");
    file.seek(position);
    file.readFully(buffer);
    return new String(buffer); // You may want to add encoding handling here
}

Edit: You can also use a loop and read a single char at a time and use a char array instead of a byte array. It would probably be simpler for you. Use the readChar method instead of read.

Switched read to readFully to guarantee that all bytes are read.

Sardtok
  • 449
  • 7
  • 18
  • I've run this code but i'm not getting the expected data Here is what I did: I have used this method and i have got [B@5b5fdf31 instead of int x=0; – Daro Royoss Jan 04 '13 at 12:13
  • Then you output the buffer directly: `System.out.println(buffer);` as the value that was output is a byte array. Converting to string is important. Also, you may want to have a look at [this question](http://stackoverflow.com/questions/14156314/how-to-access-string-in-file-by-position-in-java/14157027#14157027), where I answered how to seek using a loop (would work for Unicode). – Sardtok Jan 04 '13 at 12:18
  • See also [How to read UTF8 encoded file using RandomAccessFile](https://stackoverflow.com/questions/9964892/how-to-read-utf8-encoded-file-using-randomaccessfile) – Vadzim May 16 '19 at 16:30