Ask your own question, for FREE!
Computer Science 19 Online
OpenStudy (javk):

How do you read a text file into java?

OpenStudy (woodrow73):

``` public void readFile(String path) { File file = new File(path); if(!file.exists()) { print("Your file at path \'" + path + "\' does not appear to be a valid file."); } else { Scanner in = new Scanner(file); while(in.hasNext()) { print(in.nextLine()); } in.close(); } } ```

OpenStudy (woodrow73):

``` public void print(String str) { System.out.println(str); } ```

OpenStudy (woodrow73):

Good classes for outputting to a .txt file: PrintWriter class, and if you want to append information, the FileWriter class. Reading in is handled by the Scanner class, and the Scanner class is also useful for reading in keyboard input. Also, I forgot to put it in the code, but it needs to be in a try/catch block for IOExceptions.

OpenStudy (javk):

but how is that linking to the text file it should be getting the info from?

OpenStudy (anonymous):

I'm not sure I understand the question. you have to supply the path to the file you want to read. Here look at the example woodrow posted above here, his function gets `path` to the file you want to read

OpenStudy (javk):

ok so if I were to call it in the main method, how would I do that? is this right? ``` public static void main(String [] args) { readFile(FileName); }

OpenStudy (anonymous):

Sorry, back. Ye, just put a string for the file path instead of `FileName`. Remember that `\` is used for for escaping characters in a string, so you to take that into consideration and instead of `C:\test` do `C:\\test` for example

OpenStudy (javk):

its giving an error

OpenStudy (woodrow73):

post your full code

OpenStudy (woodrow73):

@Javk

OpenStudy (javk):

sorry :\ ``` import java.io.*; import java.util.*; import java.util.Scanner; public class Dictionary { public static void readFile(String path) throws Exception { File file = new File(path); if(!file.exists()) { print("Your file at path \'" + path + "\' does not appear to be a valid file."); } else { Scanner in = new Scanner(file); while(in.hasNext()) { print(in.nextLine()); } in.close(); } } public static void print(String str) { System.out.println(str); } public static void main(String[] args) { readFile("C:\Users\Javeria\Desktop"); } }

OpenStudy (woodrow73):

Your path is off- if you have a file called "mytextfile.txt" on your desktop, the correct path would be ``` C:\Users\Javeria\Desktop\mytextfile.txt ``` however, that will probably cause an error, because back slashes in a String represent an 'escape sequence', like doing \t will make a tab, \n will make a newline \" will be a quote, \' will be a single quote, and a \\ will be a single backslash. In Strings, you can use \\ or a single forward slash / to specify a path.

OpenStudy (javk):

I already tried that ``` public static void main(String[] args) { readFile("C:\\Users\Javeria\Desktop\user.txt"); } ``` but that was giving an error too: Invalid escape sequence (valid ones are \b \t \n \f \r \" \' \\ )

OpenStudy (woodrow73):

um, your file path contains single backslashes?

OpenStudy (woodrow73):

("C:\\Users\\Javeria\\Desktop\\user.txt");

OpenStudy (javk):

yeah that gave this : Unhandled exception type Exception

OpenStudy (woodrow73):

try throws IOException

OpenStudy (woodrow73):

If that doesn't work upload your full code again

OpenStudy (woodrow73):

Hi pitamar

OpenStudy (javk):

that didn't work but just throws exception worked though this time it says: Error: Main method not found in class Dictionary, please define the main method as: public static void main(String[] args) or a JavaFX application class must extend javafx.application.Application ``` import java.io.*; import java.util.*; public class Dictionary { public static void readFile(String path) throws Exception { File file = new File(path); if(!file.exists()) { print("Your file at path \'" + path + "\' does not appear to be a valid file."); } else { Scanner in = new Scanner(file); while(in.hasNext()) { print(in.nextLine()); } in.close(); } } public static void print(String str) { System.out.println(str); } public static void main(String[] args) throws Exception{ readFile("C:\\Users\\Javeria\\Desktop\\user.txt"); } }

OpenStudy (anonymous):

Hi woodrow lol =) Let me try and execute this. I'm using linux so the path will be a little different, but still

OpenStudy (woodrow73):

I may as well try too..

OpenStudy (woodrow73):

I don't reckon the throws Exception is needed in the main method.. I think.

OpenStudy (anonymous):

Looking at the error it seems it doesn't like the `throws exception` for main

OpenStudy (woodrow73):

funny, program compiled & ran for me.

OpenStudy (javk):

can you send exactly what you have, beginning to end?

OpenStudy (woodrow73):

``` import java.io.*; import java.util.*; public class Dictionary { public static void readFile(String path) throws Exception { File file = new File(path); if(!file.exists()) { print("Your file at path \'" + path + "\' does not appear to be a valid file."); } else { Scanner in = new Scanner(file); while(in.hasNext()) { print(in.nextLine()); } in.close(); } } public static void print(String str) { System.out.println(str); } public static void main(String[] args) throws Exception{ readFile("C:\\Users\\alex\\Desktop\\mountain.txt"); } } ```

OpenStudy (woodrow73):

Idk if you know, but make sure the java file is saved as the class name ```Dictionary.java```

OpenStudy (anonymous):

works for me too

OpenStudy (woodrow73):

make sure your file isn't actually "users.txt.txt".. and also see if a HelloWorld program compiles.. could be a jdk thing.

OpenStudy (javk):

umm..before i get into that, i just noticed, there is one slightly odd thing

OpenStudy (javk):

notice the weird red exclamation mark?

OpenStudy (woodrow73):

You should make Dictionary.java it's own project.. remember, a program can only have one main method.

OpenStudy (javk):

ooooohhh weeeelll...that wasn't embarrassing at all

OpenStudy (javk):

now that we are totally over my embarrassment, can ask something that will make you want to wring my neck? Can I read text file straight into a vector?

OpenStudy (woodrow73):

xD no worries, everyone learns this stuff at some point. Seems like you're going in the deep end pretty quick- I like it :). Define 'vector'? You can read it in as an int, yes.

OpenStudy (javk):

hey, hey only I get to diss myself :p @pitamar ok well...I have a text file which has a list of items in it. These need to go into a vector. Each item is on a separate line by it'self. The contents of the file are as below: ``` class instance object Pizza shazam Pasta implements abstract ``` well as you can see they are pretty abstract. I had been working on this all morning and then accidently permanently deleted it though I just remembered that I had a backup. So this is what I have: ``` import java.io.*; import java.util.*; import java.util.Scanner; public class Dictionary{ public static Vector <String []> fileToVector(String s) throws Exception { Vector v = new Vector(); FileReader fr = new FileReader("C:\\Users\\Javeria\\Desktop\\user.txt"); Scanner inone = new Scanner(fr); while (inone.hasNextLine()) v.addElement(inone.nextLine()); return v; } public static void main(String [] args) throws Exception{ Vector <String []> w = fileToVector(args[0]); for (int i = 0; i < w.size(); i++) System.out.println(w.elementAt(i)); } } ``` it's something I got out of the book

OpenStudy (woodrow73):

If you do read it in as an int, always put ``` in.next(); ``` after each time you read something that isn't in.nextLine();

OpenStudy (anonymous):

@Javk Lol sorry I didn't mean it in a bad way Just saying that it's normal to make mistakes and you shouldn't feel bad about it =)

OpenStudy (woodrow73):

I mean in.nextLine() after in.nextInt() and before another in.nextLine(); http://stackoverflow.com/questions/13102045/skipping-nextline-after-use-nextint

OpenStudy (woodrow73):

I'm pretty sure you can only read in Strings and data types - but don't hold me too it, check the javadocs on it. I don't know the Vector class, but there's most likely some way to transform the String into usable data for the Vector.

OpenStudy (anonymous):

Ok, so what's wrong with that code? it should add all the lines to the vector, isn't it what you want?

OpenStudy (javk):

don't wotrry @pitamar okay so i'll look at this in the morning, thankyoooooo

OpenStudy (javk):

So, I did a bit of tweaking and now the .dict file is being read into the vector: ``` import java.io.*; import java.util.*; import java.util.Scanner; public class Dictionary{ static Vector v = new Vector(); public static void readFile(String path) throws Exception { FileReader file = new FileReader(path); Scanner in = new Scanner(file); while(in.hasNext()) { v.addElement(in.nextLine()); } } public static void main(String [] args) throws Exception{ readFile("C:\\Users\\Javeria\\Desktop\\user.dict"); System.out.println(v); } }

OpenStudy (woodrow73):

Nice.. so- it works? :D also - when you put an object in System.out.println(); if the object has a toString() method, it will automatically be called. A handy function.

OpenStudy (woodrow73):

That it seems your making use of :).

Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!
Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!