Java File Input/Output - It's Way Easier Than You Think

Coding with John
26 Apr 202108:17

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

00:00

📝 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.

05:01

📖 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

BufferedWriter is a Java class used for writing text to files. It provides a buffer to the underlying writer, which means it can handle multiple write operations efficiently by collecting the data and writing it out in chunks. In the video, the instructor uses BufferedWriter to create a new object for writing data to a file called 'output.txt'. This is a fundamental concept for file output operations in Java.

💡FileWriter

FileWriter is another Java class used for writing data to files. Unlike BufferedWriter, FileWriter does not buffer the output, which means it writes data directly to the file. In the script, FileWriter is used within the BufferedWriter constructor to specify the file to which data should be written. This is crucial for understanding how data is directed to a specific file in Java's file I/O operations.

💡IOException

IOException in Java is an exception that can be thrown when an error occurs during input or output operations. In the video script, the instructor mentions that using FileWriter can result in an IOException, which needs to be handled either by a try-catch block or by declaring it in the method signature. This is an important aspect of robust Java programming, as it helps in managing runtime errors related to file operations.

💡Relative Path

A relative path is a file path that is specified relative to the current working directory of the program. In the video, the instructor writes to a file using a relative path, which means the 'output.txt' file is created in the same directory as the Java program. This is a common practice when the file location does not need to be specified absolutely.

💡Absolute Path

An absolute path is a full path that specifies the exact location of a file or directory from the root directory. In the context of the video, the instructor demonstrates how to write to a file using an absolute path, which ensures that the 'output.txt' file is created at a specific location on the computer, regardless of the program's working directory.

💡BufferedReader

BufferedReader is a Java class used for reading text from files. Similar to BufferedWriter, it provides a buffer to the underlying reader, which enhances the efficiency of reading operations by reducing the number of read calls to the file. In the video, BufferedReader is used to create an object for reading data from 'output.txt', illustrating how file input is managed in Java.

💡FileReader

FileReader is a Java class for reading character files. It provides a simple interface for reading data from files. In the video script, FileReader is used within the BufferedReader constructor to specify the file from which data should be read. This is essential for setting up file input streams in Java.

💡Resource Leak

A resource leak occurs when a resource that needs to be explicitly closed is not closed after its use, leading to potential memory or resource wastage. In the video, the instructor mentions a warning about the BufferedWriter object not being closed, which could result in a resource leak. Properly closing resources like writers and readers is crucial for preventing such leaks in Java programs.

💡Try-Catch Block

A try-catch block in Java is used to handle exceptions. The 'try' block contains code that might throw an exception, while the 'catch' block contains code to handle the exception. In the video, the instructor uses try-catch blocks around file writing and reading operations to handle potential IOExceptions, demonstrating good exception handling practices in Java.

💡New Line

In the context of text files, a new line refers to the sequence of characters that mark the end of a line of text. In the video, the instructor explains how to write multiple lines to a file by including a newline character ('\n') in the string being written. This is an important concept for formatting the output in text files.

💡Loop

A loop in programming is a structure that repeats a block of code a certain number of times. In the video, the instructor uses a 'for' loop to iterate over an array of strings and write each element to a file. Later, a 'while' loop is used to read each line from a file until the end is reached. Loops are fundamental constructs in Java for repeating operations, such as file I/O.

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

play00:00

do you need to write data to a text file

play00:01

or read data from a text file in java

play00:03

that's what we're going to do from

play00:04

scratch in this video i'm going to show

play00:06

you the simplest way to read and write

play00:07

text files in java my name is john and i

play00:09

do a new java tutorial video every

play00:11

single week so please consider

play00:12

subscribing so you don't miss each

play00:14

week's video i also have a full java

play00:15

course available in a link down in the

play00:17

description if you're interested

play00:18

if not that's awesome too i'm thrilled

play00:19

to have you here and as always the full

play00:21

source of this program is available in a

play00:23

link down in the description so go and

play00:24

get it if you look around online you're

play00:26

going to find

play00:27

tons of different ways to do file input

play00:29

and output in java so what i'm going to

play00:30

show you definitely isn't the only way

play00:33

it can be done but it is the way that i

play00:34

think is the simplest and it's the way

play00:36

that i like to use myself

play00:37

let's start with writing data to a text

play00:39

file the class that i like to use most

play00:41

for

play00:41

file output in java is called buffered

play00:44

writer

play00:45

so let's make a new buffered writer

play00:46

object we're going to call it

play00:48

writer and we say equals new buffered

play00:51

writer

play00:52

using eclipse we can go ahead and import

play00:53

buffered writer but if you aren't using

play00:55

a fancy ide

play00:56

the import is java java.io.bufferedrider

play00:59

now notice it's still complaining to us

play01:00

here because this constructor is

play01:02

undefined

play01:02

and that's because we have to actually

play01:03

pass something into this constructor

play01:05

method

play01:06

the reason it needs to take something is

play01:07

because this kind of buffered writer can

play01:08

write to many different things

play01:10

and a file is just one of them so we

play01:12

need to tell it that we want to write to

play01:13

a file and we can do that by saying new

play01:16

file writer

play01:17

and we also need to tell this file

play01:18

writer which file we want it to write

play01:20

and for that we can just pass in the

play01:22

name of the file that we want to create

play01:23

for our output file let's just call it

play01:26

output.txt we also have to import

play01:28

filewriter which is going to be

play01:30

java.io.filewriter and you might notice

play01:32

that now java is complaining that

play01:33

there's this

play01:34

unhandled exception i o exception all

play01:36

that means is that this code can throw

play01:38

an i o exception so we either need to

play01:40

handle it here in a try catch or declare

play01:42

in our main method that we throw it so

play01:44

we should do the right thing and just

play01:45

surround this code

play01:46

with a try catch block and we don't

play01:47

really need to do anything special

play01:48

inside of our catch block

play01:50

if this exception happens we can just

play01:51

print the stack trace and that's fine

play01:52

for our purposes okay

play01:54

now that our writer object has been

play01:56

created honestly the hard part's over

play01:58

all you need to do after that is take

play01:59

your writer object and call

play02:02

writer.write and you just pass in to

play02:04

this write method the string that you

play02:05

want to write to the file so let's just

play02:07

pass in

play02:07

a writing to a file but you're not done

play02:10

quite yet this won't work completely the

play02:12

way it is if you're running this in an

play02:13

ide you might notice that there's a

play02:15

warning for this writer object that says

play02:16

resource leak

play02:17

writer is never closed so what you have

play02:19

to do after you're done writing

play02:21

everything to the file

play02:22

that you want to you need to call

play02:24

writer.close

play02:25

if you forget to do that your file will

play02:27

get created but nothing will be written

play02:29

to it it'll just be blank

play02:30

and you'll be pulling your hair out

play02:31

trying to figure out what you did wrong

play02:33

and it's just this simple you need to

play02:34

remember to close your writer all right

play02:36

now let's go ahead and run it and see

play02:37

what we get

play02:38

okay the program finished successfully

play02:40

we didn't write any console output we

play02:42

just have the file output so let's go

play02:43

and see if that got created successfully

play02:45

if you just specify the file name here

play02:47

in your file writer that's what's called

play02:48

a

play02:49

relative path that just means that

play02:50

output.txt file is going to go right

play02:53

next to wherever your program is on your

play02:54

computer so if you just have a

play02:56

java file it's probably going to be in

play02:57

that same directory if you're using an

play02:59

ide like eclipse it's going to be in

play03:01

your project directory

play03:02

and you can get there very easily from

play03:04

eclipse by just right-clicking anywhere

play03:05

in this file

play03:06

and going to show in system explorer

play03:09

that will open a window that shows your

play03:10

dot java file you just need to go one

play03:12

directory

play03:13

up to go to your project folder so for

play03:15

me that's this file io folder

play03:17

and we can see that it has created this

play03:18

output.txt file so let's just open it up

play03:20

and see what's in it and it just has

play03:22

writing to a file and that's exactly

play03:24

what we wanted it to have now that's

play03:25

just one line of course let's say you

play03:27

wanted to write

play03:27

another line in that file so what you

play03:29

might try is just calling writer.write

play03:31

again and passing in whatever line you

play03:33

want to write like

play03:34

here is another line let's run that

play03:36

again

play03:37

completed successfully now one thing to

play03:39

note the first time that you run this it

play03:41

will create this output.txt file

play03:43

but every time you run it after that it

play03:45

will overwrite that same file now most

play03:47

of the time that's just fine but if

play03:48

there's something in there that you want

play03:49

just

play03:50

remember that it's going to do that it's

play03:51

going to overwrite it so just be careful

play03:53

anyway let's look at our text file and

play03:55

so what happened it actually didn't put

play03:56

this on another line and put it on the

play03:58

same line

play03:58

so what you actually have to do is put a

play04:00

backslash n whenever you want to do a

play04:02

new line

play04:02

so now with our backslash n there let's

play04:04

run our program again completed

play04:06

successfully

play04:06

and now here is another line is on the

play04:08

next line and you can just keep calling

play04:10

this right method for however many lines

play04:12

you need to write to the file but most

play04:13

of the time if you're doing file io

play04:15

you're probably not writing hard-coded

play04:17

values you probably want to write to the

play04:18

file from some variable or some array

play04:20

that you have so let's show an example

play04:22

of doing that let's say we have this

play04:23

array of strings just called names that

play04:25

has three values john carl and jerry

play04:27

well what you can do is loop through

play04:28

that array and write each element to the

play04:30

file so you just have something like for

play04:32

string name in names so for each

play04:35

iteration in this loop we can just do

play04:37

writer dot right first a new line so we

play04:40

don't just smoosh all these names onto

play04:41

one line

play04:42

and then plus name let's run that and

play04:45

you can see we have the original text

play04:46

that we wrote and then

play04:47

every element of our names array on a

play04:50

new line so that's how you output to a

play04:52

relative path where it'll put the file

play04:53

right next to wherever your program is

play04:55

but if you want to put it in some

play04:56

specific spot on your computer you just

play04:57

have to pass it an absolute path

play04:59

here's just an example of an absolute

play05:01

path on my own computer so c

play05:03

users john m example output.txt

play05:06

notice that you do have to put a double

play05:07

backslash otherwise it just won't work

play05:09

right let's run that

play05:10

and now we can see we have this

play05:11

output.txt file in this exact absolute

play05:14

path

play05:14

that we specified and it has all the

play05:16

same content in it all right so now

play05:18

we've written to a file

play05:19

and we've even gotten fancy and wrote

play05:21

the contents of an array into that file

play05:23

now let's learn how to

play05:25

read from a file so to write to a file

play05:27

we used a buffered writer so it might

play05:29

not surprise you that you read from a

play05:30

file we're going to use

play05:32

a buffered reader so buffer reader

play05:34

reader

play05:35

equals new buffered reader import for

play05:38

buffered reader

play05:39

is java dot io dot buffered reader

play05:42

similarly to the buffered writer where

play05:44

we had to pass in

play05:45

a file writer for the buffered reader we

play05:47

have to pass in

play05:48

a file reader new file reader and we

play05:51

pass in either the full or absolute path

play05:53

here again to make it simple we're just

play05:54

going to read the file that we just

play05:56

wrote so just output.txt

play05:59

import file reader which is

play06:01

java.io.filereader

play06:02

and just like the filewriter this could

play06:03

throw an exception so we also want to

play06:05

surround this with another try catch

play06:07

and we'll just have it catch i o

play06:08

exception just like the writer did and

play06:10

still just print a stack trace if any

play06:12

exceptions happen

play06:12

okay now we have our reader object

play06:14

available how do we use it

play06:16

well to read a line of text from our

play06:17

file we just call reader dot

play06:20

this this read line returns a string so

play06:22

for your purposes you might want to save

play06:24

it to a variable or something but just

play06:25

to prove that we're actually reading

play06:26

from the file

play06:27

we're going to just print it out to the

play06:29

console so system.out.printline

play06:32

reader.readline so we're going to read

play06:34

the line from the file and print it out

play06:35

to the console but before we get ahead

play06:37

of ourselves once we're done using the

play06:38

reader in our program

play06:40

we do want to call reader.close as well

play06:42

to close our reader object okay now

play06:44

let's run it and see if we are reading

play06:46

from the file

play06:46

awesome we can see that it did read the

play06:48

first line of the file that we wrote

play06:50

we just wrote writing to a file so this

play06:53

is reading it successfully

play06:54

but if you're reading a file you

play06:55

probably don't want to just read one

play06:57

line you probably want to read

play06:58

each and every line to do that of course

play07:00

you're going to want to use some kind of

play07:01

a loop and here we're going to use

play07:03

a while loop this is going to look a

play07:05

little strange but just stay with me

play07:06

before that while loop let's declare

play07:08

a string to hold each line of text as we

play07:11

read it

play07:12

then in our while loops condition we're

play07:14

actually going to have

play07:15

line equals reader.readline so for each

play07:18

iteration through the loop this is going

play07:20

to read a line of text and put it in

play07:22

this line variable but of course this

play07:24

doesn't equate to true or false so it

play07:25

doesn't really work as a while condition

play07:27

yet so what we want to add is

play07:29

not equals null so what is this doing

play07:32

it's going to read a line of text from

play07:33

our file and put that line of text in

play07:35

our

play07:36

line variable when it has reached the

play07:37

end of the file this line will turn out

play07:39

to be null because there's no other

play07:41

lines to read so we can just say

play07:42

while this line does not equal null loop

play07:45

through the file

play07:46

once the line is null we know we've

play07:47

reached the end of the file and it'll

play07:49

exit the while loop

play07:50

we can get rid of this line now where

play07:51

we're just reading a single line of text

play07:53

inside this while loop all we need is

play07:55

system.out.printline

play07:57

line so this should loop through every

play07:59

single line of our file and print it out

play08:00

to the console

play08:01

and there we go writing to a file here's

play08:03

another line john carl jerry

play08:05

that matches our output text file

play08:07

perfectly if you enjoyed this video or

play08:08

learned something please let me know by

play08:10

liking and subscribing it's the only way

play08:11

these videos get out to help more people

play08:13

and so i really do appreciate it so if

play08:14

you'll do that i'll see you next video

Rate This

5.0 / 5 (0 votes)

Связанные теги
Java ProgrammingFile I/OBufferedWriterBufferedReaderText FilesCoding TutorialJohn's CourseIDE TipsException HandlingFile Paths
Вам нужно краткое изложение на английском?