10 Replies - 69142 Views - Last Post: 20 December 2007 - 01:45 PM Rate Topic: -----

#1 Mystic  Icon User is offline

  • New D.I.C Head

Reputation: 3
  • View blog
  • Posts: 49
  • Joined: 28-August 07

Reading from specific line in text file

Posted 17 December 2007 - 02:26 AM

Good day

I would like to know how to read lines of text from a text file, starting from "X" lines from the beginning and ending "X + 5" lines after. I.E. starting from line 17 and ending on line 22.

Lets say in this text file, for arguments sake, there are 200 lines of text.

The current code i have now is so:

import java.io.*;
public class TestRead {

	/**
	 * @param args
	 */
	public static void main(String[] args) throws IOException
	{
		BufferedReader in = new BufferedReader (new FileReader("Profiles.ini"));
		
		String info = "";
		for (int i = 0; i < 12; i++)
		{
		info = in.readLine();
		System.out.println(info);
		}
		
		in.close();
	}

}


By using the possible solution to this problem :D , I assume i could WRITE information to the text file only on those lines i want.

I also want to know which is more effective, throwing exceptions or using try catch?

Thanks in advance

This post has been edited by Mystic: 17 December 2007 - 02:27 AM


Is This A Good Question/Topic? 0
  • +

Replies To: Reading from specific line in text file

#2 baavgai  Icon User is offline

  • Dreaming Coder
  • member icon

Reputation: 5882
  • View blog
  • Posts: 12,761
  • Joined: 16-October 07

Re: Reading from specific line in text file

Posted 17 December 2007 - 05:40 AM

You pretty much have the answer.

You just need to read down the line you want to start from, like so:
public static void main(String[] args) throws IOException {
	BufferedReader in = new BufferedReader (new FileReader("Profiles.ini"));
	
	String info = "";
	int startLine = 17;
	int endLine = 22;
	// read prior junk
	for (int i = 0; i < startLine; i++) { info = in.readLine(); }
	for (int i = startLine; i < endLine + 1; i++) {
		info = in.readLine();
		System.out.println(info);
	}
	
	in.close();
}



However, that is not the safeest code, since it will fail in all kinds of ways and just throw that exception. Here's a more bullet proof version. Much longer, but lacking all those surprises and demonstrating the try catch.

import java.io.*;
public class TestRead {
	public static void showLines(String fileName, int startLine, int endLine)  {
		String line = null;
		int currentLineNo = 0;

		BufferedReader in = null;
		try {
			in = new BufferedReader (new FileReader(fileName));
			
			//read to startLine
			while(currentLineNo<startLine) {
				if (in.readLine()==null) {
					// oops, early end of file
					throw new IOException("File too small");
				}
				currentLineNo++;
			}
			
			//read until endLine
			while(currentLineNo<=endLine) {
				line = in.readLine();
				if (line==null) {
					// here, we'll forgive a short file
					// note finally still cleans up
					return;
				}
				System.out.println(line);
				currentLineNo++;
			}
			
		} catch (IOException ex) {
			System.out.println("Problem reading file.\n" + ex.getMessage());
		} finally {
			try { if (in!=null) in.close(); } catch(IOException ignore) {}
		}
	}

	
	public static void main(String[] args) {
		showLines("Profiles.ini", 17,22);
	}
}



Hope this helps.
Was This Post Helpful? 0
  • +
  • -

#3 Mystic  Icon User is offline

  • New D.I.C Head

Reputation: 3
  • View blog
  • Posts: 49
  • Joined: 28-August 07

Re: Reading from specific line in text file

Posted 17 December 2007 - 12:04 PM

Thanks a lot, 100% solved :D

Now by using the information regarding the line number, I assume i could write information back into the file using only on the specified lines?

Like so:

BufferedWriter writer = new BufferedWriter(new FileWriter("Profiles.ini",true)); 

int startLine = 17;
int endLine = 22;

for (int i = 0; i < startLine; i++) { info = writer.readLine(); }
for (int i = startLine; i < endLine + 1; i++) {
	writer.write(info);
		writer.close();


This post has been edited by Mystic: 17 December 2007 - 12:05 PM

Was This Post Helpful? 0
  • +
  • -

#4 baavgai  Icon User is offline

  • Dreaming Coder
  • member icon

Reputation: 5882
  • View blog
  • Posts: 12,761
  • Joined: 16-October 07

Re: Reading from specific line in text file

Posted 17 December 2007 - 05:44 PM

Reading from and writing to the same file at the same time is problematic, if it works at all. You'll do better to write into a temporary file and them copy that file over the original.
Was This Post Helpful? 0
  • +
  • -

#5 Mystic  Icon User is offline

  • New D.I.C Head

Reputation: 3
  • View blog
  • Posts: 49
  • Joined: 28-August 07

Re: Reading from specific line in text file

Posted 18 December 2007 - 12:40 AM

Thanks a lot baavgai. In the writing to part, i meant that if i wanted to write back to the file at those specific lines, not at the same time, i would use the solution (altered a bit) to achieve this?
Was This Post Helpful? 0
  • +
  • -

#6 ericode  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 7
  • View blog
  • Posts: 112
  • Joined: 09-December 06

Re: Reading from specific line in text file

Posted 18 December 2007 - 09:08 PM

View PostMystic, on 18 Dec, 2007 - 12:40 AM, said:

Thanks a lot baavgai. In the writing to part, i meant that if i wanted to write back to the file at those specific lines, not at the same time, i would use the solution (altered a bit) to achieve this?



I just submitted a code snippet on using the RandomAccessFile class (see http://www.dreaminco...nippet1535.htm).

I think the simple way of adding to the file is not possible in the way you want it. With the RandomAccessFile, you can write to any part of the file, but you are overwriting, not inserting (as the snippet will show). I think you will have to read the file into a String, modify what you want, and then write it to another file (or just write to one file as you read from another).
Was This Post Helpful? 0
  • +
  • -

#7 Mystic  Icon User is offline

  • New D.I.C Head

Reputation: 3
  • View blog
  • Posts: 49
  • Joined: 28-August 07

Re: Reading from specific line in text file

Posted 19 December 2007 - 01:08 PM

Thanks ericode. When you mention "overwriting" I assume your referring to replacing existing data and in my case, on specific lines I that I want?
Was This Post Helpful? 0
  • +
  • -

#8 baavgai  Icon User is offline

  • Dreaming Coder
  • member icon

Reputation: 5882
  • View blog
  • Posts: 12,761
  • Joined: 16-October 07

Re: Reading from specific line in text file

Posted 19 December 2007 - 01:33 PM

View PostMystic, on 19 Dec, 2007 - 03:08 PM, said:

Thanks ericode. When you mention "overwriting" I assume your referring to replacing existing data and in my case, on specific lines I that I want?


Quick clarification. In file speak, http://www.webopedia...dom_access.html always requires the file to be made of records of identical size. If all records are the same size, then you can replace one record with another. e.g.

FileData: tla.dat
XML.DOC.RTF.LOL.



Here the record size is four and I can replace the third "record" with "WTF." by simply reading (4x3) characters in and replacing the four characters there with the four I have.

However, when you're talking lines of text, you have records with no rules for size.

From shelf.dat:
Oracle XML Handbook
Programming Pearl
Tao Te Ching
sed & awk
Analysis Patterns



Now, let's say I want to replace line three with "Mastering Regular Expressions." Now I have extra characters. How do I push everything around? The answer is that I can't. If I go with something shorter like "Refactoring" I'm still stuck because now I have letters left over in the file and I have to shrink it.

The only functional way to replace lines of text in a file is to start reading the file, while writing it elsewhere, until you get to what you want to replace. You then write what you want as a replacement and keep reading the rest, still writing. When you're done, you'll have the file with the replacements you want. You then replace the original file with the new one.

Hope this helps.
Was This Post Helpful? 0
  • +
  • -

#9 Mystic  Icon User is offline

  • New D.I.C Head

Reputation: 3
  • View blog
  • Posts: 49
  • Joined: 28-August 07

Re: Reading from specific line in text file

Posted 19 December 2007 - 02:14 PM

So in essence I have to read the whole contents of the file, manipulate in java and then write back? hmmm. Because i know the specific lines that the text appear i assume i am able to write a loop with an if statement inside, triggering the if statement if the "int LineWant" = the line number then write in my information and afterwards continue writing the rest of the information back in?
Was This Post Helpful? 0
  • +
  • -

#10 baavgai  Icon User is offline

  • Dreaming Coder
  • member icon

Reputation: 5882
  • View blog
  • Posts: 12,761
  • Joined: 16-October 07

Re: Reading from specific line in text file

Posted 19 December 2007 - 06:27 PM

View PostMystic, on 19 Dec, 2007 - 04:14 PM, said:

So in essence I have to read the whole contents of the file


Well, you usually write as you read; files can be big.

Here's some very basic code for copying a text file:
void copyTextFile(String inFileName, String outFileName) {
	BufferedReader reader = null;
	PrintWriter writer = null;
	try {
		reader = new BufferedReader(new FileReader(inFileName));
		writer = new PrintWriter(new FileWriter(outFileName));
		String  line;
		while ((line = reader.readLine()) != null) {
			writer.println(line);
		}
		writer.close();
	} catch (IOException ex1) {
	} finally {
		try { if (reader!=null) reader.close(); } catch(IOException fex1) {}
		writer.close();
	}
}



To do something clever with this, we need to put some code in the while loop. To be even more clever, it would be nice to reuse the code. Here's a class I wrote for this purpose.
import java.io.*;

public class FileSearchReplace {
	protected void  processLine(
		PrintWriter writer, int lineNumber, String line		
		) throws IOException 
	{
		writer.println(line);
	}
		
	private void process(Reader readerBase, Writer writerBase) throws IOException {
		int currentLineNo = 0;
		BufferedReader reader = null;
		PrintWriter writer = null;
		try {
			reader = new BufferedReader(readerBase);
			writer = new PrintWriter(writerBase);
			String lineIn = null;
			while ((lineIn = reader.readLine()) != null) {
				processLine(writer, ++currentLineNo, lineIn);
			}
		} finally {
			try { if (reader!=null) reader.close(); } catch(IOException fex1) {}
			writer.close();
		}
	}
	

	public void process(String inFileName, String outFileName) {
		try {
			process(new FileReader(inFileName), new FileWriter(outFileName));
		} catch (IOException ex) {
			System.err.println(ex.getMessage());
			ex.printStackTrace();
		}
	}
	
	public void processInFile(String fileName) {
		try {
			File inFile = new File(fileName);
			File tempFile = File.createTempFile("srtmp", "txt");
			process(inFile.getPath(), tempFile.getPath());
			inFile.delete();
			tempFile.renameTo(inFile);
			tempFile.delete();
		} catch (Exception ex) {
			System.err.println(ex.getMessage());
			ex.printStackTrace();
		}
	}
	
	public void processToConsole(String fileName) {
		try {
			process(new FileReader(fileName), new OutputStreamWriter(System.out));
		} catch (IOException ex) {
			System.err.println(ex.getMessage());
			ex.printStackTrace();
		}
	}
}



Here, we take that fundamental copy loop and made it call a method, passing the current writer, line number, and line text. There are also a number of ways to call this. The main process uses a fairly high level of abstraction in the reader and writer so that it can be more easily used in other places.

We can use processToConsole(String fileName) to check our code, then process(String inFileName, String outFileName) to make a file from a source file. Finally, processInFile(String fileName) to do what you're asking to do.

Here's an example of usage.
public static void main(String[] args) {
	// here's the best way to use our class
	// make a sub class and re implement processLine
	class test extends FileSearchReplace {
		protected void processLine (
			PrintWriter writer, int lineNumber, String line
			) throws IOException 
		{
			if (lineNumber==2) {
				writer.println("Refactoring");
				return;
			}
			writer.println(line);
		}
		
	}
	String fileName = "shelf.dat";
	FileSearchReplace pgm = new test();
	// to check, do this
	//pgm.processToConsole(fileName);
	
	// double check
	//pgm.process(fileName, "test1.txt");
	
	// do it!
	pgm.processInFile(fileName);
}



Hope this makes sense. Enjoy.
Was This Post Helpful? 0
  • +
  • -

#11 Mystic  Icon User is offline

  • New D.I.C Head

Reputation: 3
  • View blog
  • Posts: 49
  • Joined: 28-August 07

Re: Reading from specific line in text file

Posted 20 December 2007 - 01:45 PM

Thanks baavgai
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1