Java File Input/Output - It's Way Easier Than You Think
Summary
TLDRIn this tutorial, John teaches how to read and write text files in Java. He starts by demonstrating the use of BufferedWriter for file output, explaining how to create a file and write strings to it, including handling newlines and appending text from arrays. He then covers reading files with BufferedReader, showing how to read lines until the end of the file. John emphasizes proper exception handling and closing files to prevent resource leaks. The tutorial includes writing to both relative and absolute file paths.
Takeaways
- 📝 Learn how to read and write text files in Java from scratch.
- 👨🏫 Follow along with John's tutorial for a simple approach to file I/O in Java.
- 🔗 Subscribe to John's channel for weekly Java tutorial updates.
- 💻 Use BufferedWriter for writing data to a text file in Java.
- 📚 Import BufferedWriter using 'java.io.BufferedWriter'.
- 📄 Pass a FileWriter to the BufferedWriter constructor to specify the file for writing.
- 📑 Handle IOException by surrounding file operations with a try-catch block.
- ✍️ Use 'writer.write()' to write strings to the file.
- 🔄 Close the BufferedWriter with 'writer.close()' after writing to avoid resource leaks.
- 📁 The file is created in the same directory as your program by default.
- 🔄 Overwriting files is the default behavior when writing; be cautious if data needs to be preserved.
- 📑 Use BufferedReader to read data from a text file.
- 🔍 Import BufferedReader using 'java.io.BufferedReader'.
- 🔁 Use a while loop with 'reader.readLine()' to read through each line of the file until it returns null.
- 🗑️ Close the BufferedReader with 'reader.close()' after reading to free resources.
Q & A
What is the simplest way to read and write text files in Java according to the video?
-The video suggests using `BufferedWriter` for writing and `BufferedReader` for reading text files as the simplest way.
What class is recommended for file output in Java?
-The class recommended for file output in Java is `BufferedWriter`.
How do you create a BufferedWriter object in Java?
-You create a `BufferedWriter` object by passing a `FileWriter` object to its constructor, specifying the file you want to write to.
Why is it necessary to handle `IOException` when working with files in Java?
-It is necessary to handle `IOException` because file operations can throw an `IOException`, which needs to be caught and handled properly.
What should you do after you finish writing to a file?
-After finishing writing to a file, you should call the `close()` method on the `BufferedWriter` object to ensure that the data is written to the file.
What happens if you forget to close the BufferedWriter?
-If you forget to close the `BufferedWriter`, the file will be created but it will be blank, as the contents will not be written to it.
How can you write multiple lines to a file in Java?
-You can write multiple lines to a file by calling the `write()` method multiple times, each time including a newline character (`\n`) to start a new line.
How can you write the contents of an array to a file?
-You can write the contents of an array to a file by looping through the array and writing each element to the file on a new line.
What class is used for reading files in Java?
-The class used for reading files in Java is `BufferedReader`.
How do you read a line from a file using BufferedReader?
-You read a line from a file using `BufferedReader` by calling the `readLine()` method, which returns the next line of text from the file as a `String`.
How can you read all lines from a file until the end?
-You can read all lines from a file until the end by using a `while` loop that continues to read lines with `readLine()` as long as the returned line is not `null`.
Outlines
📝 Writing to a Text File in Java
In this segment, the tutorial focuses on the basics of writing data to a text file using Java. The host, John, introduces himself and encourages viewers to subscribe for weekly Java tutorial updates. He also mentions a full Java course available in the video description. The primary class used for file output is `BufferedWriter`. John demonstrates how to create a `BufferedWriter` object and write to a file named 'output.txt'. He explains the need to handle `IOException` with a try-catch block and the importance of closing the writer object after writing to prevent resource leaks. The segment concludes with a demonstration of writing a single line and then multiple lines to the file, including how to append a newline character.
📖 Reading from a Text File in Java
This part of the script covers reading data from a text file in Java. The host John explains how to use `BufferedReader` to read from a file. He demonstrates creating a `BufferedReader` object and reading from 'output.txt', which was previously written to in the tutorial. John shows how to read a single line and then iterates over each line in the file using a while loop, printing each line to the console. He also discusses the importance of closing the reader object after use. The segment ends with a call to action for viewers to like and subscribe for more educational content.
Mindmap
Keywords
💡BufferedWriter
💡FileWriter
💡IOException
💡Relative Path
💡Absolute Path
💡BufferedReader
💡FileReader
💡Resource Leak
💡Try-Catch Block
💡New Line
💡Loop
Highlights
Introduction to reading and writing text files in Java
Using BufferedWriter for file output
Creating a BufferedWriter object
Importing BufferedWriter and FileWriter
Handling IOException with try-catch block
Writing data to a file using writer.write()
Closing the BufferedWriter with writer.close()
Creating a file with a relative path
Writing multiple lines to a file
Writing an array of strings to a file
Writing to an absolute file path
Introduction to reading from a file using BufferedReader
Creating a BufferedReader object
Reading a single line from a file
Reading all lines from a file using a while loop
Closing the BufferedReader with reader.close()
Practical example of reading and writing files
Invitation to like and subscribe for more tutorials
Transcripts
do you need to write data to a text file
or read data from a text file in java
that's what we're going to do from
scratch in this video i'm going to show
you the simplest way to read and write
text files in java my name is john and i
do a new java tutorial video every
single week so please consider
subscribing so you don't miss each
week's video i also have a full java
course available in a link down in the
description if you're interested
if not that's awesome too i'm thrilled
to have you here and as always the full
source of this program is available in a
link down in the description so go and
get it if you look around online you're
going to find
tons of different ways to do file input
and output in java so what i'm going to
show you definitely isn't the only way
it can be done but it is the way that i
think is the simplest and it's the way
that i like to use myself
let's start with writing data to a text
file the class that i like to use most
for
file output in java is called buffered
writer
so let's make a new buffered writer
object we're going to call it
writer and we say equals new buffered
writer
using eclipse we can go ahead and import
buffered writer but if you aren't using
a fancy ide
the import is java java.io.bufferedrider
now notice it's still complaining to us
here because this constructor is
undefined
and that's because we have to actually
pass something into this constructor
method
the reason it needs to take something is
because this kind of buffered writer can
write to many different things
and a file is just one of them so we
need to tell it that we want to write to
a file and we can do that by saying new
file writer
and we also need to tell this file
writer which file we want it to write
and for that we can just pass in the
name of the file that we want to create
for our output file let's just call it
output.txt we also have to import
filewriter which is going to be
java.io.filewriter and you might notice
that now java is complaining that
there's this
unhandled exception i o exception all
that means is that this code can throw
an i o exception so we either need to
handle it here in a try catch or declare
in our main method that we throw it so
we should do the right thing and just
surround this code
with a try catch block and we don't
really need to do anything special
inside of our catch block
if this exception happens we can just
print the stack trace and that's fine
for our purposes okay
now that our writer object has been
created honestly the hard part's over
all you need to do after that is take
your writer object and call
writer.write and you just pass in to
this write method the string that you
want to write to the file so let's just
pass in
a writing to a file but you're not done
quite yet this won't work completely the
way it is if you're running this in an
ide you might notice that there's a
warning for this writer object that says
resource leak
writer is never closed so what you have
to do after you're done writing
everything to the file
that you want to you need to call
writer.close
if you forget to do that your file will
get created but nothing will be written
to it it'll just be blank
and you'll be pulling your hair out
trying to figure out what you did wrong
and it's just this simple you need to
remember to close your writer all right
now let's go ahead and run it and see
what we get
okay the program finished successfully
we didn't write any console output we
just have the file output so let's go
and see if that got created successfully
if you just specify the file name here
in your file writer that's what's called
a
relative path that just means that
output.txt file is going to go right
next to wherever your program is on your
computer so if you just have a
java file it's probably going to be in
that same directory if you're using an
ide like eclipse it's going to be in
your project directory
and you can get there very easily from
eclipse by just right-clicking anywhere
in this file
and going to show in system explorer
that will open a window that shows your
dot java file you just need to go one
directory
up to go to your project folder so for
me that's this file io folder
and we can see that it has created this
output.txt file so let's just open it up
and see what's in it and it just has
writing to a file and that's exactly
what we wanted it to have now that's
just one line of course let's say you
wanted to write
another line in that file so what you
might try is just calling writer.write
again and passing in whatever line you
want to write like
here is another line let's run that
again
completed successfully now one thing to
note the first time that you run this it
will create this output.txt file
but every time you run it after that it
will overwrite that same file now most
of the time that's just fine but if
there's something in there that you want
just
remember that it's going to do that it's
going to overwrite it so just be careful
anyway let's look at our text file and
so what happened it actually didn't put
this on another line and put it on the
same line
so what you actually have to do is put a
backslash n whenever you want to do a
new line
so now with our backslash n there let's
run our program again completed
successfully
and now here is another line is on the
next line and you can just keep calling
this right method for however many lines
you need to write to the file but most
of the time if you're doing file io
you're probably not writing hard-coded
values you probably want to write to the
file from some variable or some array
that you have so let's show an example
of doing that let's say we have this
array of strings just called names that
has three values john carl and jerry
well what you can do is loop through
that array and write each element to the
file so you just have something like for
string name in names so for each
iteration in this loop we can just do
writer dot right first a new line so we
don't just smoosh all these names onto
one line
and then plus name let's run that and
you can see we have the original text
that we wrote and then
every element of our names array on a
new line so that's how you output to a
relative path where it'll put the file
right next to wherever your program is
but if you want to put it in some
specific spot on your computer you just
have to pass it an absolute path
here's just an example of an absolute
path on my own computer so c
users john m example output.txt
notice that you do have to put a double
backslash otherwise it just won't work
right let's run that
and now we can see we have this
output.txt file in this exact absolute
path
that we specified and it has all the
same content in it all right so now
we've written to a file
and we've even gotten fancy and wrote
the contents of an array into that file
now let's learn how to
read from a file so to write to a file
we used a buffered writer so it might
not surprise you that you read from a
file we're going to use
a buffered reader so buffer reader
reader
equals new buffered reader import for
buffered reader
is java dot io dot buffered reader
similarly to the buffered writer where
we had to pass in
a file writer for the buffered reader we
have to pass in
a file reader new file reader and we
pass in either the full or absolute path
here again to make it simple we're just
going to read the file that we just
wrote so just output.txt
import file reader which is
java.io.filereader
and just like the filewriter this could
throw an exception so we also want to
surround this with another try catch
and we'll just have it catch i o
exception just like the writer did and
still just print a stack trace if any
exceptions happen
okay now we have our reader object
available how do we use it
well to read a line of text from our
file we just call reader dot
this this read line returns a string so
for your purposes you might want to save
it to a variable or something but just
to prove that we're actually reading
from the file
we're going to just print it out to the
console so system.out.printline
reader.readline so we're going to read
the line from the file and print it out
to the console but before we get ahead
of ourselves once we're done using the
reader in our program
we do want to call reader.close as well
to close our reader object okay now
let's run it and see if we are reading
from the file
awesome we can see that it did read the
first line of the file that we wrote
we just wrote writing to a file so this
is reading it successfully
but if you're reading a file you
probably don't want to just read one
line you probably want to read
each and every line to do that of course
you're going to want to use some kind of
a loop and here we're going to use
a while loop this is going to look a
little strange but just stay with me
before that while loop let's declare
a string to hold each line of text as we
read it
then in our while loops condition we're
actually going to have
line equals reader.readline so for each
iteration through the loop this is going
to read a line of text and put it in
this line variable but of course this
doesn't equate to true or false so it
doesn't really work as a while condition
yet so what we want to add is
not equals null so what is this doing
it's going to read a line of text from
our file and put that line of text in
our
line variable when it has reached the
end of the file this line will turn out
to be null because there's no other
lines to read so we can just say
while this line does not equal null loop
through the file
once the line is null we know we've
reached the end of the file and it'll
exit the while loop
we can get rid of this line now where
we're just reading a single line of text
inside this while loop all we need is
system.out.printline
line so this should loop through every
single line of our file and print it out
to the console
and there we go writing to a file here's
another line john carl jerry
that matches our output text file
perfectly if you enjoyed this video or
learned something please let me know by
liking and subscribing it's the only way
these videos get out to help more people
and so i really do appreciate it so if
you'll do that i'll see you next video
浏览更多相关视频
Writing and Appending to Files in PHP in Hindi | PHP Tutorial #37
What is a file path and why does it matter
Python Pandas Tutorial 4: Read Write Excel CSV File
Comments, Escape Sequences & Print Statement | Python Tutorial - Day #5
Core Java With OCJP/SCJP-java IO Package-Part 2 || File I/O
Basic Linux Navigation
5.0 / 5 (0 votes)