Easy-to-follow video tutorials help you learn software, creative, and business skills.Become a member
Once you've learned the core principles of Java, you'll find that expanding your knowledge of the language is a matter of learning about more classes and their functionality. One of the most common tasks that all programmers need to know how to do in any programming language is how to work with files. So in this chapter, I'll go through a number of different programming tasks including copying files, deleting them, writing them from scratch, and so on. And I'll start with how to copy an existing file. I'm going to be using a number of classes from the core class library called the input stream, file, and output stream.
My project, FileManagement, has a single text file and it just has some nonsense text in it. My goal is to write some code that copies this file and create a new file with the same contents. I'll do all the work in the Main method of this class, CopyFile. The first step is to create objects that represent your existing file and the file you want to create and for this purpose, we use a class named file. I'll type in the name of the class and press Ctrl+Space and choose the version of file from java.io and I'll name it f1.
I'll instantiate class and I'll pass in the name of the existing file, loremipsum.txt. When you're working with a console application, you can assume that the file is in the project directory that is the root directory where the whole project is stored. If you are working in another programming environment such as Java Enterprise Applications that is web applications, the rules for where the current directory is may differ; check the documentation for that environment. Next I'll create a second file variable and I'll have this file object refer to the file I want to create, I will call it target.txt.
So a file object can refer either to an existing file or when you want to create. Next, I'll create classes called input and output streams. An input stream can read the contents of a file and an output stream can write the contents of a file. I'll declare a variable data typed as InputStream, I'll press Ctrl+Space and choose InputStream from java.io. I'll name it in and I'll instantiate it using a specific class called FileInputStream.
The Java.io package has many versions of the input stream class. This one is specifically for files and when I instantiate the file input stream, I'll pass in the file reference. Next, I'll create an output stream. I'll follow the same pattern, I'll type the name of the class and press Ctrl+Space and be very specific hear; there's more than one version of the output stream class available to you, you want the version in java.io. Name the output stream out and instantiate it using FileOutputStream.
Once again I'm making sure I select the class from the list so I get my import statement, and I'm referencing file number 2. You'll see that there are errors over on the side, don't worry about them from now; we'll take care of them at the end of all the programming. The next step is to create objects that we can use to read the contents of the file. In Java, in order to copy a text file, you copy a byte by byte. There is no single method in the core Java class library to say copy a file and you have a choice of reading one byte at a time or using a chunk of bytes at a time.
It's more efficient to use a chunk of bytes, but you don't want to use too many bytes because you don't want to chew up memory. So in the next step, I'm going to create an array of bytes and give it a specific size, large enough but not too large. I'll declare a variable as a byte array, I'll give it a name of buf for buffer, and I'll instantiate it using new byte . That's a nice little number. It means that I'm going to read 1024 bytes at a time.
Next, I'll declare a variable named len for length, data type as in int. I'll use that to determine how many bytes I get back each time I read something from the file. If I'm just starting to read the file, the byte array will contain 1024 bytes. When I get to the end of the file, len will return the total number of bytes remaining and this will make sure that I don't try to write bytes to the target file that I don't have. Now I'll create a loop with the while keyword. I'll use off while loop with condition and here's the condition.
I'll start with an open parenthesis then len = in.read(buf), and then I'll compare the return value to 0, and close the whole condition with a closing parenthesis. So this part of the expression means reading of information from the source file to fill the byte array that will be 1024 bytes maximum and then return the total number of bytes that you actually got to the integer variable, len.
If the value that's returned is greater than 0 then that means we got something. If the value returned is 0 that means we're done, we're at the end of the file. Once again, you'll see an error; again, don't worry about it. We'll deal with that at the end. So now I have an array of bytes that I can use to write content to the target file and I'll use this syntax, out. write, I'll pass in the buffer byte array, a beginning point of 0 of the byte array and len, the number of bytes that I want to output.
And that's it; I'm done copying the file over. Before I can really be finished though, I need to close my streams. Input and output streams can use resources. Not all output streams and input streams actually use resources, but it's a good practice to call a method on each of them called close. So I'll use in.close and out.close and finally, I'll output a message saying that the file was copied.
Now let's get to all these errors; if you move the cursor over all the error indicators, you'll see that they're all saying that they are unhandled exceptions. Some of them indicate IOException and some of them indicate FileNotFoundException. You can handle all these exceptions with a single try catch, I'm going to select all the code, right click, and then choose Surround With>Try Catch Block. And you'll see that there are catch blocks added for both possible exceptions; FileNotFound and IOException.
So now my code should be ready to run and we'll see what happens. I'll run the application, I get the message, file copied. I'll go over to the Package Explorer, right-click, and choose Refresh and I see my new target file has been successfully created. Now, you might be thinking that's an incredibly complex way to copy a file. But this is how you do it using the core Java class library. The good news is that there are libraries out there in the world from the Apache Commons project that make this kind of process a whole lot easier.
I'll show you how to download and use that particular library later in the course, but it's important to know how to do this in the raw form in Java so that if you have to write your own specific code, you'll know how.
Get unlimited access to all courses for just $25/month.Become a member