New Feature: Playlist Center! Pick a topic and let our playlists guide the way.

Easy-to-follow video tutorials help you learn software, creative, and business skills.Become a member

Managing files with the core class library

From: Java Essential Training

Video: Managing files with the core class library

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.

Managing files with the core class library

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 [1024]. 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.

Show transcript

This video is part of

Image for Java Essential Training
Java Essential Training

71 video lessons · 66694 viewers

David Gassner
Author

 
Expand all | Collapse all
  1. 10m 8s
    1. Welcome
      1m 3s
    2. Is this course for you?
      5m 35s
    3. Using the exercise files
      3m 30s
  2. 31m 24s
    1. The history of Java
      5m 19s
    2. Java compilation and syntax
      8m 54s
    3. Understanding the principles of Java
      8m 28s
    4. Choosing a development environment
      8m 43s
  3. 19m 5s
    1. Installing Java on Windows
      6m 42s
    2. Installing Eclipse on Windows
      3m 19s
    3. Exploring Java on Mac OS X Leopard and Snow Leopard
      2m 27s
    4. Installing Java on Mac OS X Lion
      3m 27s
    5. Installing Eclipse on Mac OS X
      3m 10s
  4. 46m 10s
    1. Creating a Hello World application
      11m 7s
    2. Exploring the Eclipse IDE
      8m 55s
    3. Compiling and running from the command line
      8m 2s
    4. Passing arguments to the application
      8m 17s
    5. Using the Java API documentation
      4m 5s
    6. Memory management and garbage collection
      5m 44s
  5. 58m 57s
    1. Everything is an object
      5m 59s
    2. Declaring and initializing variables
      9m 15s
    3. Working with numbers
      8m 32s
    4. Converting numeric values
      6m 40s
    5. Understanding operators
      7m 58s
    6. Working with character values
      5m 14s
    7. Working with boolean values
      5m 13s
    8. Outputting primitive values as strings
      5m 33s
    9. Creating a simple calculator application
      4m 33s
  6. 53m 40s
    1. Writing conditional code
      5m 35s
    2. Using the switch statement
      8m 50s
    3. Repeating code blocks with loops
      7m 35s
    4. Creating reusable code with methods
      6m 31s
    5. Declaring methods with arguments
      5m 41s
    6. Overloading method names with different signatures
      5m 53s
    7. Passing arguments by reference or by value
      5m 35s
    8. Creating a more complex calculator application
      8m 0s
  7. 20m 30s
    1. Using the String class
      5m 44s
    2. Building strings with StringBuilder
      3m 34s
    3. Parsing string values
      3m 19s
    4. Working with date values
      7m 53s
  8. 20m 44s
    1. Understanding compile-time vs. runtime errors
      4m 5s
    2. Handling exceptions with try/catch
      4m 55s
    3. Throwing exceptions in methods
      2m 50s
    4. Using the debugger
      8m 54s
  9. 32m 22s
    1. Using simple arrays
      4m 47s
    2. Using two-dimensional arrays
      6m 17s
    3. Managing resizable arrays with ArrayList
      7m 14s
    4. Managing unordered data with HashMap
      6m 5s
    5. Looping through collections with iterators
      7m 59s
  10. 52m 2s
    1. Understanding encapsulation
      5m 59s
    2. Creating and instantiating custom classes
      8m 8s
    3. Organizing classes with packages
      6m 47s
    4. Creating and using instance methods
      6m 52s
    5. Storing data in instance variables
      6m 56s
    6. Using constructor methods
      5m 40s
    7. Managing instance data with getter and setter methods
      8m 26s
    8. Using class variables and Enum classes
      3m 14s
  11. 41m 15s
    1. Understanding inheritance and polymorphism
      9m 12s
    2. Extending custom classes
      9m 1s
    3. Overriding superclass methods
      3m 8s
    4. Casting subclass objects
      5m 3s
    5. Understanding interfaces and implementing classes
      4m 2s
    6. Creating your own interfaces
      4m 14s
    7. Using abstract classes and methods
      6m 35s
  12. 32m 17s
    1. Managing files with the core class library
      7m 46s
    2. Managing files with Apache Commons FileUtils
      7m 32s
    3. Reading a text file from a networked resource
      7m 52s
    4. Parsing an XML file with DOM
      9m 7s
  13. 17m 39s
    1. Creating your own JAR files
      4m 54s
    2. Understanding the classpath
      5m 2s
    3. Documenting code with Javadoc
      7m 43s
  14. 47s
    1. Goodbye
      47s

Start learning today

Get unlimited access to all courses for just $25/month.

Become a member
Sometimes @lynda teaches me how to use a program and sometimes Lynda.com changes my life forever. @JosefShutter
@lynda lynda.com is an absolute life saver when it comes to learning todays software. Definitely recommend it! #higherlearning @Michael_Caraway
@lynda The best thing online! Your database of courses is great! To the mark and very helpful. Thanks! @ru22more
Got to create something yesterday I never thought I could do. #thanks @lynda @Ngventurella
I really do love @lynda as a learning platform. Never stop learning and developing, it’s probably our greatest gift as a species! @soundslikedavid
@lynda just subscribed to lynda.com all I can say its brilliant join now trust me @ButchSamurai
@lynda is an awesome resource. The membership is priceless if you take advantage of it. @diabetic_techie
One of the best decision I made this year. Buy a 1yr subscription to @lynda @cybercaptive
guys lynda.com (@lynda) is the best. So far I’ve learned Java, principles of OO programming, and now learning about MS project @lucasmitchell
Signed back up to @lynda dot com. I’ve missed it!! Proper geeking out right now! #timetolearn #geek @JayGodbold

Are you sure you want to delete this note?

No

Thanks for signing up.

We’ll send you a confirmation email shortly.


Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

Keep up with news, tips, and latest courses with emails from lynda.com.

Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

   
submit Lightbox submit clicked
Terms and conditions of use

We've updated our terms and conditions (now called terms of service).Go
Review and accept our updated terms of service.