Results 1 to 7 of 7
Like Tree2Likes
  • 2 Post By JosAH

Thread: Need help file reading a txt file (Emergency)

  1. #1
    765891 is offline Member
    Join Date
    Jan 2013
    Location
    San Antontio, Texas, US
    Posts
    17
    Rep Power
    0

    Exclamation Need help file reading a txt file (Emergency)

    //new to file reading i have no clue
    //i tried learning today from an java 6 SE website please i have a competition
    //tommorrow and file reading is mandatory
    //can anyone please check over this and see where im messing up?
    //how do i make all parts of the txt file show up becuase currently
    //only one line is showing up and its showing and error
    //Error: U:\Lab report\textfile.txt (The system cannot find the path specified)
    //this is the runtime error im recieving, the file is in the correct place
    Java Code:
    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("I:\\OddEven.java");
    		  // 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);
    			  
    			  Writer output;
    			  output = new BufferedWriter(new FileWriter("I:\\Lab report\\textfile.txt"));
    			  output.append("New Line!");
    			  output.close();
    			  
    		  }
    		  //Close the input stream
    		  
    		  in.close();
    	  }
    	  catch (Exception e)
    	  {
    	  	//Catch exception if any
    	  	System.err.println("Error: " + e.getMessage());
    	  }
      }
    }
    Last edited by 765891; 02-28-2013 at 12:34 AM.

  2. #2
    AndrewM16921 is offline Senior Member
    Join Date
    Jan 2009
    Location
    NJ, USA
    Posts
    261
    Rep Power
    6

    Default Re: Need help file reading a txt file (Emergency)

    There are a LOT of ways to read a file with java. I usually use a BufferedReader wrapped around a FileReader, though I'm not sure if this is the best way.
    Also, Java 7 offers some nice features when dealing with resources (such as BufferedReader).

    The error you are receiving is because the file or directory you are trying to read from doesn't exist (or can't be accessed). Do you have an I: drive? Also, what OS are you using?

    Here's a quick example:

    Java Code:
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileReader;
    import java.io.IOException;
    
    public class Reading
    {
    	private static final String filename = "I:" + File.separator + "OddEven.java";
    	
    	public static void main(String[] args)
    	{
    		read6();
    		read7();
    	}
    	
    	// Java 6
    	public static void read6()
    	{
    		File file = new File(filename); // "file.txt" in local directory
    		BufferedReader in = null;
    		try
    		{
    			in = new BufferedReader(new FileReader(file));
    			String line; // represents the last read line from the full
    			while((line = in.readLine()) != null) // loop until no more lines
    			{
    				// do something with the line that was read
    				System.out.println(line);
    			}
    		}
    		catch(IOException e) // if the file doesn't exist
    		{
    			System.err.println("The file " + file.getAbsolutePath() + " does not exist!");
    		}
    		finally
    		{
    			if(in != null)
    			{
    				try
    				{
    					// close Reader if not null
    					in.close();
    				}
    				catch(IOException e)
    				{
    					e.printStackTrace();
    				}
    			}
    		}
    	}
    	
    	// Java 7
    	public static void read7()
    	{
    		File file = new File(filename); // "file.txt" in local directory
    		
    		// "try with resource" automatically closes resources
    		try(BufferedReader in = new BufferedReader(new FileReader(file)))
    		{
    			String line; // represents the last read line from the full
    			while((line = in.readLine()) != null) // loop until no more lines
    			{
    				// do something with the line that was read
    				System.out.println(line);
    			}
    		}
    		catch(IOException e) // if the file doesn't exist
    		{
    			System.err.println("The file " + file.getAbsolutePath() + " does not exist!");
    		}
    	}
    }
    Last edited by AndrewM16921; 02-27-2013 at 06:45 AM.

  3. #3
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,189
    Rep Power
    19

    Default Re: Need help file reading a txt file (Emergency)

    765891, please go through the Forum Rules, particularly the second paragraph. I've removed the thread you startd in the JCreator section. Also go through Guide For New Members and BB Code List - Java Programming Forum - Learn Java Programming and edit your psot accordingly.

    db
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  4. #4
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    12,999
    Blog Entries
    7
    Rep Power
    19

    Default Re: Need help file reading a txt file (Emergency)

    What is the 'emergency'? I don't see any blood ...

    kind regards,

    Jos
    DarrylBurke and 765891 like this.
    cenosillicaphobia: the fear for an empty beer glass

  5. #5
    Art Vandelay is offline Member
    Join Date
    May 2012
    Posts
    18
    Rep Power
    0

    Default Re: Need help file reading a txt file (Emergency)

    Hi 7,

    Here is a file utility I made to read files. I put this in a java file called FileUtils.java along with a host of other similar utils.

    Java Code:
    	/**
    	* This method reads any text file.
    	* @param filename	the name of the file you wish to view
    	*/
    	public void readFile( String filename ) {
    
    		String next = "";
    		String linesInS = "";
    		StringBuffer linesInSB = new StringBuffer( );
    		try{
    			BufferedReader buf = new BufferedReader( new FileReader( filename ) );
             	while(true) {
             	   next = buf.readLine();
            	   if(next==null) break;
             	   linesInSB.append( next );
             	}
             	buf.close( );
    		}
    		catch( IOException ioe ) {
    			System.out.println( "Error reading text file" );
    			System.out.println( ioe );
    		}
    
    		linesInS = linesInSB.toString( );
    
    	}

  6. #6
    765891 is offline Member
    Join Date
    Jan 2013
    Location
    San Antontio, Texas, US
    Posts
    17
    Rep Power
    0

    Default Re: Need help file reading a txt file (Emergency)

    Thank you sir you mistyped "post"

  7. #7
    765891 is offline Member
    Join Date
    Jan 2013
    Location
    San Antontio, Texas, US
    Posts
    17
    Rep Power
    0

    Default Re: Need help file reading a txt file (Emergency)

    I asked my comp sci teacher and showed me some faster code
    I learned you can do it with just scanner, much fast however that method i was learning was much safer.
    When I asked my Comp sci 3rd year student they didn't even know buffered reading, because my teacher showed them file reading through scanner.
    I had this code saved on my USB, that's why I have a I: Drive, Window's 7 Home Premium .
    I realized the error, i was trying to open 2 files at once, but i didn't set it up.
    // output = new BufferedWriter(new FileWriter("I:\\Lab report\\textfile.txt")); <<<< Problem
    //FileInputStream fstream = new FileInputStream("I:\\OddEven.java");
    Thank you Andrew and Art vandelay


    Java Code:
    import java.io.*;
    import java.util.*;
    import static java.lang.System.*;
    
    
    public class ScannerFilesPrac
    {
    
    	public static void main(String args[]) throws IOException
    	{
    		//Set the Scanner object to the file's exact location. Make sure the 
    		//		file is in the same folder as the class.
    		Scanner file = new Scanner(new File("numbers.txt"));
    
    		//Read the first number in the file.  This will represent the number of 
    		//		values to expect.  SEE FILE
    		int cnt = file.nextInt();
    		
    		file.nextLine();   		//clear the buffer 
    
    
    		for(int i=0; i < cnt; i++)
    		{  
    		   //Read the next number and display
    		   int num = file.nextInt();
    		   
    		   file.nextLine();		//clear the buffer 
    		   
    		   String title = file.nextLine();
    		   out.println(num + "\t" + title);
    		}
    
    
    	}
    }
    Last edited by 765891; 02-28-2013 at 12:58 AM.

Similar Threads

  1. Replies: 0
    Last Post: 12-15-2012, 01:37 AM
  2. Reading file external to jar file
    By nn12 in forum New To Java
    Replies: 6
    Last Post: 02-04-2011, 05:46 AM
  3. reading a file and writing to a file....help!!!!
    By java_prgr in forum New To Java
    Replies: 3
    Last Post: 07-26-2010, 06:53 PM
  4. Replies: 9
    Last Post: 10-20-2009, 10:52 AM
  5. Replies: 3
    Last Post: 05-09-2009, 11:31 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •