Files


DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

Page 1 of 2 12 LastLast
Results 1 to 15 of 18

Thread: Files

  1. #1
    Join Date
    Sep 2005
    Posts
    74

    Files

    Here is my code:

    Code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.io.*;
    import java.text.NumberFormat;
    
    public class FileStats extends JFrame
    {
    	public static JTextArea display;
    	
    	public FileStats()
    	{
    		super("Testing FileStats program");
    		display = new JTextArea();
    		getContentPane().add(display, "Center");
    		
    	}// FileStats()
    	
    	/* pre: args has command-line arguments
    	 * post: both files in args have been closed;
    	 *       max, min, count, sum have been calculated
    	 * calls: doStats
    	 */
    	public static void readFile(String[] args) throws IOException
    	{
    		// Get file name arguments from the command line as entered by the user
    		String inFileName = args[0];
    		String outFileName = args[1];
    		
    		try
    		{
    			// Prepare files
    			BufferedReader inFile = new BufferedReader(new FileReader(inFileName));
    			PrintWriter outFile = new PrintWriter(new FileWriter(outFileName));
    			
    			// Read and write from input and output files
    			String testInfo = inFile.readLine();
    			outFile.println("Results " + testInfo);
    			outFile.println();
    			
    			String num = inFile.readLine();
    			
    			while (num != null)
    			{
    				doStats(num, inFile, outFile);
    				num = inFile.readLine();
    			}// while()
    
    			// Close the files
    			inFile.close();
    			outFile.close();
    			
    		} catch (FileNotFoundException e){
    			display.setText("IOERROR: File NOT Found " + inFileName + "\n");
    			e.printStackTrace();
    		} catch (IOException e){
    			display.setText("IOERROR: " + e.getMessage() + "\n");
    			e.printStackTrace();
    		}// end try/catch block
    		
    		display.append("Program completed.  Close window to exit program.\n");
    		
    	}// readFile()
    	
    	 /* pre: num has a value
    	  * post: max, min, count, sum have been set or reset
    	  */
    	public static void doStats(String num, BufferedReader inFile,
                PrintWriter outFile) throws IOException
    	{
    		int number;
    		int count = 0;
    		int sum = 0;
    		int countOfNums = 0;
    		int max = 0;
    		int min = 0;
    		
    		while (count != 14)
    		{
    			number = Integer.parseInt(inFile.readLine());
    			sum += number;
    			countOfNums++;
    			if (max > number)
    			{
    				max = number;
    			} else {
    				max = 0;
    			}// if()
    			if (min < number)
    			{
    				min = number;
    			} else {
    				min = 0;
    			}// if()
    			
    			count++;
    		}// while()
    		
    		outFile.println("sum " + sum);
    		display.append("sum" + sum + "\n");
    		outFile.println("count " + countOfNums);
    		display.append("count" + countOfNums + "\n");
    		outFile.println("max " + max);
    		display.append("max" + max + "\n");
    		outFile.println("min " + min);
    		display.append("min" + min + "\n");
    		
    	}// doStats()
    	
    	public static void main(String[] args) throws IOException
    	{
    		FileStats fileStat = new FileStats();
    		readFile(args);
    		fileStat.setSize(400, 300);
    		fileStat.setVisible(true);
    		fileStat.addWindowListener(new WindowAdapter() {
    
                public void windowClosing(WindowEvent e){
    
                      System.exit(0);
    
                }
    
          });
    	}// main()
    }// FileStats
    For some reason I'm getting an ArrayIndexOutOfBoundsException. I have a file called numbers.dat with a 13 numbers in it, and I'm trying to read from it, preform operations on the numbers, and output the results to both the JFrame and a new file. Can someone shed some light on what I'm doing wrong?
    Last edited by Dark Rain; 01-21-2006 at 01:28 PM.

  2. #2
    Join Date
    Sep 2005
    Posts
    74
    I figured out how to get rid of the ArrayIndexOutOfBounds error, but now another error showed up. Here is the error message:

    Code:
    Exception in thread "main" java.lang.NumberFormatException: null
    	at java.lang.Integer.parseInt(Unknown Source)
    	at java.lang.Integer.parseInt(Unknown Source)
    	at FileStats.doStats(FileStats.java:89)
    	at FileStats.readFile(FileStats.java:54)
    	at FileStats.main(FileStats.java:122)
    Why is this happening?

  3. #3
    Join Date
    Dec 2005
    Location
    New Jersey
    Posts
    290
    Probably because you are doing Integer.parseInt() on a null String.

  4. #4
    Join Date
    Sep 2005
    Posts
    74
    Hmm. The file I'm trying to work on (numbers.dat) has 13 numbers in it. The first number is -18, and the rest are just random numbers. I wonder why it thinks that I'm trying to parse a null string...

  5. #5
    Join Date
    Dec 2005
    Location
    New Jersey
    Posts
    290
    You're probably reading one line too many. I don't have time to look at your code, but are you making sure it only reads 13 numbers?

  6. #6
    Join Date
    Jan 2006
    Posts
    53
    Off the top of my head, this block...

    Code:
    String num = inFile.readLine();
    			
    while (num != null)
    {
    	doStats(num, inFile, outFile);
    	num = inFile.readLine();
    }// while()
    I would usually write this way:

    Code:
    String num;
    
    while( (num = inFile.readLine()) != null )
    {
    	doStats(num, inFile, outFile);
    }

  7. #7
    Join Date
    Jan 2006
    Posts
    53
    ...But that's not your problem.

    First, you're looking for 15 numbers when you set up your loop like this:
    Code:
    int count = 0;
    while (count != 14)
    {
        ...
        count++;
    }
    Second, in your readFile method, you have already done 2 readLine() calls, which causes you to skip on of the numbers altogether, and leaves you with only 11 numbers to parse.

    So take out at least one of the readLine calls before the loop in readFile, and make sure you're only looking for 12 numbers in doStats. Something like this:

    Code:
    int count = 0;
    while(count<12)
    {
        ...
        count++;
    }
    As for this while loop, I'd suggest using a for loop. But the results are the same, so using while isn't causing you any problems, per se.

    I'd also suggest you move the BufferedReader and PrintWriter declarations outside of the try{} block, and put the calls to their close() methods a finally{} block. It's still not ideal, but it's much better. And at least you'll be able to see some of your output in the output file even when you get exceptions.

  8. #8
    Join Date
    Sep 2005
    Posts
    74
    Is there a way specifically to check if the file has reached its end (no more numbers)? That way one could add as many numbers as they wanted and it would still work.

    Also, the program seems to be counting the numbers in the file from the bottom up. The top two numbers are not being counted into the total sum, and if they are removed the program ceases functioning. So the above method of checking for the end of the file would be very helpful.

    Thank you for the help so far, at least the program is running now =p.
    Last edited by Dark Rain; 01-23-2006 at 06:42 PM.

  9. #9
    Join Date
    Dec 2005
    Location
    New Jersey
    Posts
    290
    If you use the scanner class you can do something like this:
    Code:
    Scanner scanner = new Scanner(new File(inFileName));
    
    //...
    
    while (scanner.hasNextInt()) {
        number = scanner.nextInt();
        // ...
    }
    More info on the scanner class here.

    You can also look at what Laszlo said and do something like this:
    Code:
    String line;
    while ((line = inFile.readLine()) != null);
        number = Integer.parseInt(line);
        // ...
    }

  10. #10
    Join Date
    Jan 2006
    Posts
    53
    when readLine() returns a null, as opposed to a "", it has reached the end of what is available. In stead of a counter in your while loop, you could put the readLine() in the while statement in doStats.

    Something like:
    Code:
    String line;
    while( (line = inFile.readLine()) != null)
    {
        number = Integer.parseInt(line);
       ...
    }
    And have a look at the min and max methods in java.lang.Math. They're very handy.

  11. #11
    Join Date
    Dec 2005
    Location
    New Jersey
    Posts
    290
    Quote Originally Posted by Laszlo
    when readLine() returns a null, as opposed to a "", it has reached the end of what is available. In stead of a counter in your while loop, you could put the readLine() in the while statement in doStats.

    Something like:
    Code:
    String line;
    while( (line = inFile.readLine()) != null)
    {
        number = Integer.parseInt(line);
       ...
    }
    And have a look at the min and max methods in java.lang.Math. They're very handy.
    hahaha looks like we're on the same page

  12. #12
    Join Date
    Sep 2005
    Posts
    74
    If I do that I'll be duplicating the while loop found in readFile(). How can I modify the loop in readFile() so I'm not duplicating it? Sorry for all the questions, my instructor basically threw down a bunch of code and didn't explain it, so I'm kind of lost.

  13. #13
    Join Date
    Jan 2006
    Posts
    53
    The loop in readFile is superfluous. All the min/max calculations are done on local variables iside doStats, so the loop in readFile is pretty much useless, unless there's some element of design and requirements that you haven't mentioned yet.

  14. #14
    Join Date
    Sep 2005
    Posts
    74
    One more question. For some reason the program is not reading the first number in the file. No matter what I put there, the sum of the values stays the same as if the first number was 0. Does me initializing sum to 0 before the loop have any bearing on this?

    EDIT: Putting a space before the number list in the file fixes the problem. Why is this so?

  15. #15
    Join Date
    Jan 2006
    Posts
    53
    I don't know. You have this line:

    String testInfo = inFile.readLine();

    and also this line:

    String num = inFile.readLine();

    They're both correct syntax. I cut-and-pasted your code into my IDE and it works for me. I faked a data file, made the first line a -18, and added 12 lines of random integers. The -18 ended up in testInfo and the next line (which happened to be a 123) ended up in num. In the code you posted, num is never used for anything, but was being set. <shrug>

Similar Threads

  1. How to manage PAK files in vb programs?
    By Melawen in forum VB Classic
    Replies: 6
    Last Post: 04-17-2005, 05:56 AM
  2. XML files vs Database
    By Mansoor in forum Enterprise
    Replies: 2
    Last Post: 09-10-2002, 10:38 PM
  3. XML files vs Database
    By Mansoor in forum XML
    Replies: 8
    Last Post: 08-23-2002, 04:35 PM
  4. Replies: 0
    Last Post: 03-13-2001, 01:54 PM
  5. Replace In Files utility released
    By René Whitworth in forum vb.announcements
    Replies: 1
    Last Post: 04-29-2000, 02:54 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center
 
 
FAQ
Latest Articles
Java
.NET
XML
Database
Enterprise
Questions? Contact us.
C++
Web Development
Wireless
Latest Tips
Open Source


   Development Centers

   -- Android Development Center
   -- Cloud Development Project Center
   -- HTML5 Development Center
   -- Windows Mobile Development Center