HomeЛюди и блогиRelated VideosMore From: thenewboston

Java Programming Tutorial - 81 - Reading from Files

2548 ratings | 504990 views
Facebook - https://www.facebook.com/TheNewBoston-464114846956315/ GitHub - https://github.com/buckyroberts Google+ - https://plus.google.com/+BuckyRoberts LinkedIn - https://www.linkedin.com/in/buckyroberts reddit - https://www.reddit.com/r/thenewboston/ Support - https://www.patreon.com/thenewboston thenewboston - https://thenewboston.com/ Twitter - https://twitter.com/bucky_roberts
Html code for embedding videos on your blog
Text Comments (370)
akram md (1 day ago)
thanks man very mach *
dudentp (7 days ago)
i dont think this works anymore. I copied the code exactly and get errors after a run it
Dani Gol (1 month ago)
I know how to add records to Chinese, but dont know how to add it in a separate line. sorry for the stupid Q in advance
a name (1 month ago)
does this work if spacing is in issue?
Michael Ly (1 month ago)
It threw the exception of could not find file for me.
Nasser_Omar (2 months ago)
thanks bro good job
Laurens Ohl (2 months ago)
Could somebody tell me, if this is actually still the way you do it? I’m often not quite sure if those clips are outdated…
GrammWorld (3 months ago)
why does ti finds an error at System.out.printf("%s", a);
Erick Jeremmy (3 months ago)
why don't you read the values from the keyboard? we not interesting to read from the list
KoalaOnCaffeine (3 months ago)
0:58 at first you had my attention, now you have my interest!
I.N.R Gaming (3 months ago)
for some reason in the text file its seperated but when i write everything to print the value out it prints everything sticked to eacother like this: 22ishaqzarour 25Janemain
cody Tremblay (4 months ago)
Can you do this with images?
Chethan Prabhu (4 months ago)
where is that chineese file located.. pls tell me
Sid L (4 months ago)
Awesome!! Great explanation with example. Thanks for the video. Cheers, http://www.flowerbrackets.com/how-to-find-length-of-a-string-in-java/
Randy Bushman (5 months ago)
Hey, so i have a quick question. I am using a FileInputStream on an existing text file and am using the .read() method to print out the contents of that file. For whatever reason I would get a value back that has nothing to do with the text written in the file. For example, when I typed the number 5 into the text file (5 being the only thing written in the text file) I would get back the number 35 when I tried printing it. Same with the letter C, I just got back the number 43. Is there anybody that can give me an in depth reason why this happens?
Nur Afza (5 months ago)
how to create "chinese.txt"?
Kabira Suleman (5 months ago)
is this direct access
Ryan (6 months ago)
Scanners don't work to read text files. At all!
Saswati Bhattacharjee (6 months ago)
Sir, Can you give me your mail id.This is a file related problem in java. I want to share my code with you to find out the error. This code is related to my final year project. My mail id: [email protected]
Clint Distad (7 months ago)
best explanation i have had yet.
Ven BlueDragon (8 months ago)
Hello Bucky, I would like to get a few tips from you, Could you help me as quick as possible, thanks for replying soon, and just send me your email add, and I will ask you my question in regards with JAVA Programming. Thanks for your prompt reply
Victor Marquez (8 months ago)
It is a very clear man, but I need to know, in my case I do have three field in the txt file; course, credit and title, which title is much longer field, see below: IT2249 6 Introduction to Programming with Java IT2230 3 Introduction to Database Systems IT4789 3 Mobile Cloud Computing Application Development I am having issue to display the third field which is title. Can you help?
salma N (7 months ago)
Victor Marquez Try making the titles have the same length .. I had a similar problem but in C
Saswati Bhattacharjee (9 months ago)
Hello Sir, I have a data file where all values are in floating type.You use String a=x.next(); I want to read this datatype as double so I change this line as double a= x.next(); But it is throw an exception like Error:(22, 30) java: incompatible types: java.lang.String cannot be converted to double. So can you suggest me a way to solve it.
Tan Boon Wei (9 months ago)
Is overwriting files and creating files using the same code?
Joel Hubahib (9 months ago)
Great tutorial Bucky!. Do you have buffered reader/writer and filewriter?
Patrascu Lucian (11 months ago)
Why would one want to create, write or read files in java when we have Operating Systems?
supamayn17 (11 months ago)
Thank you thank you
Matthew Adams (11 months ago)
Instead of using the try/catch statement, you can include a throws clause in your main header: public static void main(String[] args) throws FileNotFoundException{
milhaus jaukl (11 months ago)
Hi, i am using Scanner for user input but you are using for search file or what ? Can you comment this or little help :( Sorry for my bad english Thanks
milhaus jaukl (11 months ago)
Oh i am sorry. i have already known
Erickk isreal (1 year ago)
For some reason my txt program say the file is not available even though it's in my src folder
Pablo Biedma (1 month ago)
save it in you project folder, not in the src one
John Lima (1 year ago)
You didn't say how to write multiple registers in the last lesson.
Joe Smith (1 year ago)
You're much better at teaching compared to my uni lecture and tutor.
ronnie chan (1 year ago)
Is this the same for .dat files?
Meraj Khan (1 year ago)
I wonder how rich this guy is.
Wycliffe Kiprop (1 year ago)
thanks.. this is great! I have managed to read my file using this procedure. now I would like little assistance to move to the next step, where I want to scan and select a specific values in column 'a' and print out its corresponding value in column 'b'. Thanks.
Loading (1 year ago)
It sounds like you were coding outside.
Sushan Shakya (1 year ago)
Can u please tell me all the extensions supported by SCANNER while reading from a file (For eg: myfile.php , myfile.txt) ......???
kamel abbad (1 year ago)
woooow u are sooo coool man tghanx u soo much for u are tuto
Dimitris Ladakis (1 year ago)
What if I want the intact lines from the file as opposed to splitting each line in words??
ForFyve Ziro (1 year ago)
thanks m8
ManOFSteel (1 year ago)
bucky , joe , mike & sis are chinese?? LOL!
TNTSquid (1 year ago)
Can i ask.... Why is that called Chinese.txt ....
Jan Tabara (1 year ago)
Hi, what if I had the same example, but added a constructor? That would mean I need to initialize the scanner prior to its usage in the openFile() method. Would it be correct to create new scanner in that constructor and then create another one in the openFile() method? Because if I don't do that, I get a nullpointer exception.
Abhishek Singh (1 year ago)
x = new Scanner(new File("I:\\Java\\Java_practise\\src\\chinese.txt")); above method works when your file is placed inside the src folder. while, if your file is placed outside the src or bin folder then u have to use below method x = new Scanner(new File("chinese.txt"));
Alex Gutierrez (1 year ago)
just saved me from a huge headache, thanks for making it painless.
Jorge Suarez (1 year ago)
Idk why I can't hear this on my desktop but I can hear it on my phone.
Brittany Ference (1 year ago)
Is there an easy to way to read multiple txt files at once?
Cheezy Egwuuie (1 year ago)
how to you add or subtract the numbers after reading the txt file  and put answers in a new column
Mario Ključević (1 year ago)
I need help. If anyone can explain me how to I save file data to a string variable. In this example, Bucky just outputs them on screen using printf, but I want to save those data for further work. Thanks :)
tHE vIbE (1 year ago)
i can't get program to work! ERROR! Exception in thread "main" java.lang.NullPointerException at readfile2.readFile(readfile2.java:18) at readfile1.main(readfile1.java:6) keeps pointing me at these 2 lines: while(x.hasNext()){ r.readFile();
Mathura (1 year ago)
Hi, Anyone could give a solution for this assignment? Create a method that reads a comma separated file that contains 10 rows of comma separated title, genre and releaseDate. This method should return an Array of Movie
rcard53762 (1 year ago)
I type the code exactly as shown and I get an error when I include the public void closeFile() If I leave that out I dont get the error.
Ayush Mishra (1 year ago)
Wait, the program isn't able to find my file- WHAT DO I DO: and yes, I did spell it correctly -_-
ziiip (1 year ago)
Is it in the src folder of your project or elsewhere.
Ayush Mishra (1 year ago)
How do you read specifically one line, because what I am trying to do is make a program read a file that has different data given in each line. Thanks in advance...
B Sumanth (1 year ago)
use nextLine() instead of next()
umskyld (2 years ago)
thank you :)
Mihai Grec (2 years ago)
What if the lines are irregular?For example on 1st line we have 6 numbers,on 2nd line we have 4 numbers and on 3rd line we have 2 strings
SDV (2 years ago)
while (x.hasNext()) { String line = x.nextLine(); System.out.println(line); } or while (x.hasNext()) { System.out.println(x.nextLine()); }
ElectricPyroclast (2 years ago)
The bird and cricket sounds in the background, tho
Nico Z (2 years ago)
Using the formatter, How do you move to the next line in the text file? did you \n?
Muushuu Pip (2 months ago)
Use %n after %s, \n doesn't work with the formatter
GILBERT AYEBARE (2 years ago)
thanks a lot sir ,but how can i now be able to compare two records using regex,other wise nice time
Andres Hurtado (2 years ago)
so how did you make that chinese.txt tab?
Ya Dad (2 years ago)
Just open the txt file in eclipse
DerpyAce1 (2 years ago)
Thank you for the Help. Very explanatory and easy to follow through. Keep it up.
Joeffrey Galon (2 years ago)
How i can use file writter and reader at the same time ? "I want to make a search out of a file, then when the file is found. i write data on file then i want to read it automatically" i have already done getting the search and writting... i cant figure out how to use write and read at the same time
theSYNQmaster (2 years ago)
Dunno why, but it always throws an exception in my case. I'm using this in a static context, does this make any difference?
theSYNQmaster (2 years ago)
+Supetorus I remember I managed to fix it somehow but can't remember how I did it. It's a while ago now. Thanks for the help anyway :)
Supetorus (2 years ago)
do you mean you are doing readFile.openFile() and from your main method, or do you mean you are trying to use Scanner.hasNext() and stuff like that from the readFile class? If it's the latter you have to use a Scanner object to access the instance data. You can't access instance from static. If you are doing the former but you didn't declare your methods as static it could also be the problem. I'm not an expert so not sure about any of that but I hope it helped.
Aaron Hansen (2 years ago)
Javaturial! :)
Muneeb Afzal (2 years ago)
Mine isn't working this is the code I run:public class ReadingFromFiles {        public static void main(String[] args) {                 NewClass r = new NewClass();         r.openFile();         r.readFile();         r.closeFile();   }     }// This is in a different classpublic class NewClass {         private Scanner x;         public void openFile(){                 try{             x = new Scanner (new File ("MuneebAfzal.txt"));         }         catch(Exception e){             System.out.println("Could not find file");         }     }                  public void readFile(){         while (x.hasNext()){             String a = x.next();             String b = x.next();             String c = x.next();         System.out.printf("%s %s %s", a,b,c);          }     }         public void closeFile(){         x.close();     } }The error I get says Exception in thread "main" java.lang.NullPointerException  at reading.from.files.NewClass.readFile(NewClass.java:23)  at reading.from.files.ReadingFromFiles.main(ReadingFromFiles.java:12) C:\Users\Muneeb\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53: Java returned: 1 BUILD FAILED (total time: 0 seconds)Thanks, I've imported the relevant functions
ivan jaya (2 years ago)
Hai Bucky, how to insert those string from text file to the linked list? So the first line is linkedlist1, the second line is linkedlist2, etc. Is it possible to do that? Thanks.
Atlas Horne (2 years ago)
vry useful 4 a game im making. But why did u make a tutorial at 2 AM?
Cpt. Doge (2 years ago)
excellent work, helped me a lot
i love your voice heheh thanks for the tutorial !
mamba (2 years ago)
mine does not run these are my erros please help Exception in thread "main" java.lang.NullPointerException at readfile.readFile(readfile.java:22) at ReadFileEx.main(ReadFileEx.java:9) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
Nicolas Soto (2 years ago)
What about a user inputting a word to search for in file?
xAJarrett (2 years ago)
+Nicolas Soto Programming is problem solving and asking questions is part of it :)
Nicolas Soto (2 years ago)
+xAJarrett Lol, pretty basic and simple now that I think about it.
xAJarrett (2 years ago)
+Nicolas Soto Read all the lines and check them against a string
spiralings (2 years ago)
excellent vids. got the answer I needed 0.5 seconds into the video "import java.io.*;" my throws FileNotFoundException was red. thanks again, you rock!
xAJarrett (2 years ago)
+spiralings Try CTRL + SHIFT + O next time :)
Dj Laing (2 years ago)
says "file" not declared
Shamak (2 years ago)
You probably need to capitalize "File".
Ludwig (2 years ago)
The weirdest thing is that you don't have to specify the file extension in this case. Just "chinese" works, instead of "chinese.txt"
joseph Lordi (2 years ago)
Saad Alenany You method works better especially when the variables have multiple words with spaces. Thanks. I'm bucky isn't watching this any more but THANKS YOU ARE A JEM.
Itachi Uchiha (2 years ago)
Fan Chen (2 years ago)
I got it and thanks so much
Saad Alenany (2 years ago)
//another way instead of creating more variables , but nice work Bucky >>> you're still the best 😉 public void readFile(){ while(x.hasNext()){ System.out.print(x.nextLine()+"\n"); } }
徐宏杰 (4 months ago)
Tudor Lechintan try this,while(x.hasNextline)
徐宏杰 (4 months ago)
instead of while(x.hasNext),you should write while (x.hasNext);your readFile method will convert all content into a row
Maiwand (1 year ago)
thank you for saving me about 3 hrs of time
Karthikeyan K (1 year ago)
this is what i had as a doubt!! thkzz
Energized Gaming Guy (1 year ago)
Nayan Raut (2 years ago)
x = new Scanner (new File ("C:\\folder\\abc.txt"));
Kamal Patel (2 years ago)
Can somebody help me whenever i read from file i get everything in capital even if i put text "Hello" like this.
Alex Moore (2 years ago)
is there a way you can put the full code up because this looking part to part is not working for me
Soundhar Natarajan (2 years ago)
pls let me know if u know the answer I am searching for it for more than a month
Soundhar Natarajan (2 years ago)
I mean can we make an interaction with our own Java application with PowerPoint is there any jar files for that
Soundhar Natarajan (2 years ago)
how to open pptx files using Java application
Wasim Bader (2 years ago)
thank you sir for the teachings. sir
205PROSS (2 years ago)
say for instances you wanted to add all the A variables how would I go about doing that?
Niharika Sinha (3 years ago)
what do i do if i want to store the three separate fields in three separate string arrays? i.e. a, b and c should be String arrays holding all their respective fields of the records?
xAJarrett (2 years ago)
+Niharika Sinha It's the same approach, just different data type. So you use a String array. Here's what the loop would look like: while(x.hasNext()){    a[count] = x.next();    b[count] = x.next();    c[count] = x.next();    System.out.printf("%s %s %s \n", a[count],b[count],c[count]);    count++;   } Anyone else interested should try figuring out the rest. The code is the same, you just need to initialise the string arrays.
Ilias Liakopoulos (3 years ago)
Guys,i had the same error and i changed x = new Scanner(new File("chinese.txt")); to x = new Scanner(new File(" Path of chinese.txt")); For example, path = C://Users//user//Desktop//a.txt now it works!
Tim Manno (10 months ago)
The file chinese.txt needs to be saved in the same directory as your source code or it wont compile..
M RS (11 months ago)
Yes! The reason is because when he did it he had "Chinese.txt" in the same folder as his program so the compiler knew where to access it. Whereas if you don't have it in the same folder you must specify the entire path.
Mr2Blinky (1 year ago)
Thank you !
J Maine (1 year ago)
Heck yea! .. thanks man!
Rabeya Tapasy (1 year ago)
thanks a lot
Karen Overbay (3 years ago)
can I just say your video series is helping me pass Java II class! Thank you...thank you...thank you!
Joao Amaral Pereira (3 years ago)
Mamali Rap (3 years ago)
how my bro u so aswome man i need your help please show us how we can read the data and make on data what ever we wanna do. do you have any idea about data .we try to open data but when we open it show just words you don,t can even read :) man .please if u know how we can read dose words and we can change some thinks on it if even any one know,s please make video for at less 100000 peoples wanna know s until now no one made any video for read the data files to read or writ on it .thats good to learn man thanks for ur video by the way nice one i hope u know about data too bro v:))
Why I get this error? Here is the code and the error I get: import java.io.*; import java.util.*; public class MySecondProject{ private Scanner scan; public void openFile(){ try{ scan = new Scanner(new File("starcraft.txt")); } catch(Exception e){ System.out.println("Couldn't read a file"); } } public void readFile(){ while(scan.hasNext()){ String a = scan.next(); String b = scan.next(); String c = scan.next(); System.out.printf("%s%s%s\n",a,b,c); } } public void closeFile(){ scan.close(); } } Couldn't read a file Exception in thread "main" java.lang.NullPointerException at MySecondProject.readFile(MySecondProject.java:14) at MyFirstProject.main(MyFirstProject.java:5)
Christopher Koester (9 months ago)
StarCraft, eh? Adun tori dus!
FlawlessPants (2 years ago)
+Назар Панченко Just change your input to (starcraft)); instead of (starcraft.txt)); it seems that the newer versions only allow you to write the name of the file and not the type.
+Назар Панченко Well, I already figured out what was the cause of the problem. Just needed to specify the absolute path for a file. Now it works
Sebastian Borromeo (3 years ago)
The problem is when you try to read "chinese.txt" Just change your scanner input to chinese private Scanner x; public void openFile(){ try{ x=new Scanner(new File("chinese")); instead of try{ x=new Scanner(new File("chinese.txt")); it seems that the newer versions only allow you to write the name of the file and not the type. hope it's any help, i broke my head for 2 hours trying to solve that prob.
Dawood Chaudary (3 years ago)
+Sebastian Borromeo its still giving me error bro ??
Adam Thompson-Sharpe (3 years ago)
Doesn't work
Tim Romanski (3 years ago)
What if you had a file with more lines, and each line has a different amount of words, how would you read those lines?
Gaurav Kumar (3 years ago)
Why did we use Scanner to read the file and not the formatter? Scanner doesn't have a role in readFile() method.
Anirban Chatterjee (3 years ago)
U are the best teacher ..... Wonder why your name is "Bucky"....could have been "Brendon" LOL Anyway...u r awesome !!!!
Sebastian Borromeo (3 years ago)
+Anirban Chatterjee his name is Greg
Mau (3 years ago)
+Anirban Chatterjee lol he uses Bucky as a pseudonym btw
Alexander Al Basosi (3 years ago)
This guy is so awesome crickets are paying their tribute.
Shridhar Chini (3 years ago)
where can i get this source code..i didn't find this code in above link,..please help
Johann (3 years ago)
+Shri Chini You don't just get the source code. They want you to do it yourself... But if you're too lazy you can use my test code... It works perfectly for me. Code: import java.io.*; import java.util.*; import java.io.*; import java.util.*; public class ReadFile { public Scanner scanner; public static String status = "Preparing to read file..."; public void printStatus() { System.out.println(status); } public void openFile() { status = "Opening file..."; printStatus(); try { scanner = new Scanner(new File("text.txt")); } catch (Exception e) { status = "Failed to open the file."; printStatus(); } } public void readFile() { if (status != "Failed to open the file.") { status = "Reading file..."; System.out.println("Files text..."); printStatus(); while(scanner.hasNext()) { String text = scanner.next(); System.out.println(text); } System.out.println("-------------------"); } else { status = "Could not read file."; } } public void closeFile() { if (status == "Reading file...") { status = "Closing file..."; printStatus(); scanner.close(); } else { System.out.println("The file could not be closed, the file was never opened..."); } } } And the other class: class Main { public static void main(String[] args) { ReadFile r = new ReadFile(); r.openFile(); r.readFile(); r.closeFile(); } }
Mohamed Althaf (3 years ago)
Thanks for the great free tutorials. Here, I'm having a problem in running this code,It'll be a big help, if you point me out where I made the problem. Code: ........................................................................................................................... import java.util.*; import java.io.*; import java.lang.*; class readfile{ private Scanner s; void openFile(String directory){ String input = directory;  try{ s = new Scanner(new File(input)); } catch(Exception e3){ System.out.println("Error"); } } void readFile(){ while(s.hasNext()){ String a = s.next(); String b = s.next(); String c = s.next(); System.out.println(a+"\t"+b+"\t"+c); } } void closeFile(){ s.close(); } } // ******************************************************************** class createfile{ protected Formatter y; void createFile(String directory){ try{ y = new Formatter(directory); System.out.println("the file is created"); }catch (Exception E1){ System.out.println("Error found"); } } void writeFile(String info){ y.format(info); System.out.println("The info was added to the file"); } void closeFile(){ y.close(); } } // ********************************************************************** class searchfile{ private File x; void searchFile(String directory){ x = new File(directory); if(x.exists()){ System.out.println(x.getName() +" is exist in the directory"); }else{ System.out.println("File Not Found"); } } } // *********************************************************************** public class Files{ public static void main(String args[]){ readfile read = new readfile(); createfile create = new createfile(); searchfile search = new searchfile(); /*create.createFile("C:\\Users\\NEON Works\\Desktop\\hello.txt"); search.searchFile("C:\\Users\\NEON Works\\Desktop\\hello.txt"); create.writeFile("Hello World"); create.closeFile(); */ read.openFile("C:\\Users\\NEON Works\\Desktop\\hello.txt"); read.readFile(); read.closeFile(); } } ..................................................................................................................... END

Would you like to comment?

Join YouTube for a free account, or sign in if you are already a member.