2

I have a text file with the following contents:

one
two
three
four

I want to access the string "three" by its position in the text file in Java.I found the substring concept on google but unable to use it.

so far I am able to read the file contents:

import java.io.*;
class FileRead 
{
 public static void main(String args[])
  {
  try{
  // Open the file that is the first 
  // command line parameter
  FileInputStream fstream = new FileInputStream("textfile.txt");
  // Get the object of DataInputStream
  DataInputStream in = new DataInputStream(fstream);
  BufferedReader br = new BufferedReader(new InputStreamReader(in));
  String strLine;
  //Read File Line By Line
  while ((strLine = br.readLine()) != null)   {
  // Print the content on the console
  System.out.println (strLine);
  }
  //Close the input stream
  in.close();
    }catch (Exception e){//Catch exception if any
  System.err.println("Error: " + e.getMessage());
  }
  }

}

I want to apply the substring concept to the file.It asks for the position and displays the string.

 String Str = new String("Welcome to Tutorialspoint.com");
 System.out.println(Str.substring(10, 15) );
6
  • Please do not wrap a DataInputStream with a Reader. You don't need the DataInputStream so remove it. vanillajava.blogspot.co.uk/2012/08/… Commented Jan 4, 2013 at 11:31
  • I want to give the program 2 substring positions and it returns me the string from the text file. Commented Jan 4, 2013 at 11:33
  • Do you want to output a specific line? Or may the position be something else than a line number? Commented Jan 4, 2013 at 11:43
  • No i dont want to output a specific line. For e.g public class Test { public static void main(String[] args) { String str = "University"; System.out.println(str.substring(4,7)); } } The output is "ers" My program should take the 2 positions and display the string in the file having that position. If i put (str.substring(4,7)); The result should be "wo th" according to the text file. Commented Jan 4, 2013 at 11:58
  • Edit your question to add clear info on what you expect and what your exact problem is. Be as narrow as possible Commented Jan 27, 2013 at 2:38

3 Answers 3

3

If you know the byte offsets within the file that you are interested in then it's straightforward:

RandomAccessFile raFile = new RandomAccessFile("textfile.txt", "r");
raFile.seek(startOffset);
byte[] bytes = new byte[length];
raFile.readFully(bytes);
raFile.close();
String str = new String(bytes, "Windows-1252"); // or whatever encoding

But for this to work you have to use byte offsets, not character offsets - if the file is encoded in a variable-width encoding such as UTF-8 then there's no way to seek directly to the nth character, you have to start at the top of the file and read and discard the first n-1 characters.

Sign up to request clarification or add additional context in comments.

2 Comments

or just use 'InputStream.skip(numberOfBytes)'
@JayC667 and double-check the return value to ensure that it really did skip the number of bytes you asked it to - skip is allowed to skip fewer than numberOfBytes.
0

look for \r\n (linebreaks) in your text file. This way you should be able to count the rows containing your string.

your file in reality looks like this

one\r\n
two\r\n
three\r\n
four\r\n

5 Comments

in this way am able to do it.but i want to access lets say the sting " three " in the file by its 2 positions the start and end position. Am not directly searching for the string.
so your position is row and lineStartIndex and lineEndIndex?
better: start = row + lineStartIndex and end = row + lineEndIndex. care that it doesn't become negative!
Newlines are encoded in different ways on different platforms. \r\n is specific to Windows and x86 BIOS mode strings, \n is used n Unix-like OSes and \r on Macs (not sure if the latter is still the case with OS X which is BSD-based). Therefore you shouldn't rely on files containing \r\n for linefeeds.
entirely true, but it seems to me that there are more basic things to get aware of first (for now at least).
0

You seem to be looking for this. The code I posted there works on the byte level, so it may not work for you. Another option is to use the BufferedReader and just read a single character in a loop like this:

String getString(String fileName, int start, int end) throws IOException {
    int len = end - start;
    if (len <= 0) {
        throw new IllegalArgumentException("Length of string to output is zero or negative.");
    }

    char[] buffer = new char[len];
    BufferedReader reader = new BufferedReader(new FileReader(fileName));
    for (int i = 0; i < start; i++) {
        reader.read(); // Ignore the result
    }

    reader.read(buffer, 0, len);
    return new String(buffer);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.