File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Text File Parse - Code comments please Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Text File Parse - Code comments please" Watch "Text File Parse - Code comments please" New topic

Text File Parse - Code comments please

Jonathan Storey

Joined: May 14, 2007
Posts: 7
Hey all.

Would someone please have a look at my class that simply parses a text file and converts it to a List<String>. I am really after code comment (i.e. its ok but you should - that kind of comment) as I am trying to improve. Thanks,

[HENRY: Added Code Tags]
Vikas Kapoor
Ranch Hand

Joined: Aug 16, 2007
Posts: 1374
You can add some validations like
- check whether the file exists or not.
- file type

to make your program robust.
Christophe Verré

Joined: Nov 24, 2005
Posts: 14688

It's generally a good idea to close files in a finally block, to make sure it's going to be closed.

[My Blog]
All roads lead to JavaRanch
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199

In practice I'd usually rather see this as a single method:

public List<String> parseFileToList(File theFile) throws IOException { ...

Aside from the missing validation mentioned above, I'd say this is well done.

[Jess in Action][AskingGoodQuestions]
Jonathan Storey

Joined: May 14, 2007
Posts: 7
Thanks all for the replies. One question though, what is the best way to check the file type? I assume that you did not mean the .ext as a check?

Lucas Franceschi
Ranch Hand

Joined: Nov 10, 2008
Posts: 106

try something like this

understanding this code:
  • first, on line 4, we get the name of your file.
  • then, on line 5, we get the last position of the string "." on your string fileName
  • so if the index is not 0 (line 6) then you make a substring (line 10).

  • to make the substring, you get by first character (that will be included in the resulting string) the dotIndex (that holds the position of the last dot (.)) and you dont specify a last character, so that you'll have a string that goes from "." to the end of the fileName, now you have the extension.

    of course it may not be the best way, but I always use this.


    Lucas Franceschi
    Software Developer for SGI Sistemas,
    I agree. Here's the link:
    subject: Text File Parse - Code comments please
    jQuery in Action, 3rd edition