Results 1 to 6 of 6
  1. #1
    nhmllr's Avatar
    nhmllr is offline Member
    Join Date
    Aug 2011
    Posts
    51
    Rep Power
    0

    Default File IO reader outside of main?

    So I have a project with a few classes, including the one with the main() in it, but in my project I want to read from a .txt file from the user.

    Here's a class (tested in a separate project) that I wrote to read a text file (it is the first I've ever made, so it might not be good)

    Java Code:
    import java.io.FileReader;
    
    public class reader
    {
    	public static void main(String[] args) throws Exception
    	{
    		FileReader fr = new FileReader("textfile.txt");
    		
    		String string = "";
    		
    		int ch;
    		do
    		{
    			ch = fr.read();
    			if (ch != -1)
    			{
    				string += (char) ch;
    			}
    		} while (ch != -1);
    		
    		fr.close();
    		
    		System.out.println(string);
    	}
    }
    Now, usually with multiclassed projects you can put what would be int he main() in the constructor, and have the main() in a different class that creates the new class. But that doesn't work here.

    How can I get a text reader that reads the text in it's constructor and doesn't need the main?

  2. #2
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default Re: File IO reader outside of main?

    That program is more of a "text printer".

    There are two ways to go. The first is just to call the main() method from wherever you like. main() is not special in any way.

    Java Code:
    public class MyOtherApp 
    {
        public static void main(String[] args) throws exception 
        {
            reader.main();
        }
    }
    Note that reader should really be called Reader. And the .class file has to be accessible to the other program - since you are not using packages this means that Reader.class has to be in the same directory as MyOtherApp.class.

    The other way is to create a class out of what you have. It could be given a constructor to make it a little more useful:

    Java Code:
    public class Cat 
    {
        public Cat(String filename) throws Exception
        {
            String string = "";
             
            int ch;
            do
            {
                ch = fr.read();
                if (ch != -1)
                {
                    string += (char) ch;
                }
            } while (ch != -1);
             
            fr.close();
             
            System.out.println(string);
        }
    }
    Then use this class as you would any other:

    Java Code:
    public class MyOtherApp 
    {
        public static void main(String[] args) throws exception 
        {
            new Cat("anyfile.txt");
        }
    }
    -----

    You're right, it's not such a good file printing program. (All those string concatenations!) But I guess that's no so much the point. Rather (1) main() is not special and (2) Build even small utilities as classes with well defined "functionality". What I mean is that it would have been better for the Cat constructor to just take the filename argument and store it as an instance variable. Then it could have a doCat() method or whatever to do the actual file printing. Or it could return the string. Or... anything else you wanted. Better to write the programs this way than shove everything into a main() method.

  3. #3
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,524
    Blog Entries
    7
    Rep Power
    20

    Default Re: File IO reader outside of main?

    Quote Originally Posted by nhmllr View Post
    Now, usually with multiclassed projects you can put what would be int he main() in the constructor, and have the main() in a different class that creates the new class. But that doesn't work here.
    Why "doesn't it work"? Reading from a file isn't an exceptional action ...

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  4. #4
    nhmllr's Avatar
    nhmllr is offline Member
    Join Date
    Aug 2011
    Posts
    51
    Rep Power
    0

    Default Re: File IO reader outside of main?

    Thanks for responding!
    Your way does work really well.

    I just have two questions:

    Why do you need a "throws Exception" next to the main?
    Is there a better way to read it than with concatenation? I knew it was a bad way when I did it...

  5. #5
    nhmllr's Avatar
    nhmllr is offline Member
    Join Date
    Aug 2011
    Posts
    51
    Rep Power
    0

    Default Re: File IO reader outside of main?

    To JoshAH:

    I think it's just because I didn't have the "throws Exception" part next to the main

  6. #6
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default Re: File IO reader outside of main?

    Why do you need a "throws Exception" next to the main?
    The question really is why did you have throws Exception in the original main(). I was only copying ;) I guess the reason is that reading can give rise to i/o exceptions (someone unplugs the drive etc), and you had declared the method to throw Exception rather than IOException. Either way once you declare a method or constructor to throw an exception like that it has to be caught (with try/catch) or the method using it has also to throw the exception.

    It's explained in detail in the Exceptions chapter of Oracle's Tutorial.

    Is there a better way to read it than with concatenation? I knew it was a bad way when I did it...
    Again the best place to go would be the tutorial: in particular the Basic I/O material. Look for "buffered streams". Also find out about StringBuilder: the basic approach would be to read the file a line at a time and append the line to a string builder.

Similar Threads

  1. java file reader, jgrasp can't find the file
    By aramiky818 in forum New To Java
    Replies: 3
    Last Post: 04-22-2011, 02:06 AM
  2. Excel File Reader
    By Subhransu in forum Advanced Java
    Replies: 6
    Last Post: 03-02-2011, 09:30 AM
  3. problem with file reader
    By Stormrage in forum New To Java
    Replies: 7
    Last Post: 05-15-2010, 11:48 PM
  4. [SOLVED] Need help with file reader
    By syed.shuvo in forum New To Java
    Replies: 6
    Last Post: 09-27-2008, 07:43 PM
  5. help with file reader
    By jason27131 in forum New To Java
    Replies: 1
    Last Post: 08-01-2007, 03:03 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
  •