Sign in to follow this  
drackill

Java read from a file

Recommended Posts

Hello I'm using the follwing code to read from a txt file. This is just a crappy practice thing I did to play with it. { FileInputStream fin; System.out.println("The Text below is being read from myfile.txt in java folder\n"); try { fin = new FileInputStream ("myfile.txt"); System.out.println( new DataInputStream(fin).readLine()); System.out.println( new DataInputStream(fin).readLine()); System.out.println( new DataInputStream(fin).readLine()); fin.close(); } catch (IOException e) { System.err.println ("Unable to find the bloody file"); System.exit(-1); } Just wondering how I can specify which line to read from rather than having to put System.out.println( new DataInputStream(fin).readLine()); for each line? Cheers I have looked all over but just not had any luck in finding any tutorials or anything like that. Thanks in advance

Share this post


Link to post
Share on other sites
1° DataInputStream.readLine( ) is a deprecated function. You should be using a BufferedReader object (built around and InputStreamReader object based on the file stream).

2° Call the readLine( ) function once for each line before the line you want to reach.

3° There is no way to skip lines in a file other than reading all lines one after another. The only skipping you can do without reading characters is skipping a given number of characters, using the skip( ) function.

Share this post


Link to post
Share on other sites
Also: Whether you're wrapping with a BufferedReader, DataInputStream or anything else, you don't need to (and shouldn't!) recreate an object for each reading of a line.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this