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

Reading a text file from a networked resource

From: Java Essential Training

Video: Reading a text file from a networked resource

The class library that's a part of the JDK includes a rich set of classes designed for network communications. Among the tasks that they support, they give you the ability to easily retrieve and read files over the web. I'll show you one approach to doing this, using the classes of the Java class library. I'll mention before I get started, that there are easier ways that require less code if you use the Apache Commons Library, but it's good to know what's available in the core class library first. I'm working in a project called NetworkFiles and a class called Read network file and I'm working with an empty main method.

Reading a text file from a networked resource

The class library that's a part of the JDK includes a rich set of classes designed for network communications. Among the tasks that they support, they give you the ability to easily retrieve and read files over the web. I'll show you one approach to doing this, using the classes of the Java class library. I'll mention before I get started, that there are easier ways that require less code if you use the Apache Commons Library, but it's good to know what's available in the core class library first. I'm working in a project called NetworkFiles and a class called Read network file and I'm working with an empty main method.

The first step in getting a network file is knowing its location. You should wrap the location in the file in an instance of a class named URL for Uniform Resource Locator. I'll type in the name of the class which is all uppercase and I'll press Ctrl + Spacebar, and choose the version in the package java.net. I'll name that variable url, all lowercase and then instantiate it, using the URL constructor method, I'll start with a pair of quotes. Now the purpose of the URL class is to wrap a string that indicates the location of the file, so now I need the file.

I'll go to Internet Explorer, I'm going to be retrieving a dynamic XML feed from the web. Here is the URL http://services. explorecalifornia.org/RSS/tours.php. When you view this file in a browser, its format will differ from one browser to the next. In the Internet Explorer, it might be formatted the way you see here on the screen or if you're working in Chrome or Firefox, it might have a hierarchical presentation.

But regardless of how it's presented visually the actual format is XML. You can see this in any browser by right clicking and choosing view source or some similar menu choice. That will open the raw format of the retrieved content and you'll see that it's an XML file and you also see that it's in RSS format. RSS is the format that's used for syndicated content. For example, if somebody has a site that's based on WordPress, typically you'll be able to get an RSS feed of their content from that site.

So now that I've confirmed that this URL provides a valid XML feed, I'll copy the URL to the clipboard and return to Eclipse. I'll place the cursor inside double quotes that I use to pass in the value to the URL and I'll paste in the URL string. I'll maximize my editor so we can see all the code. You'll see an error occur over on the left, it's telling you about a potential unhandled exception, we'll deal with that later. The next step is to create an instance of a class named InputStream.

I worked with this class in an earlier video, when I opened a file from the local file system. It's the same data type but this time I am going to create the reference to the object by calling a method of the URL class using URL.openStream. So now I have my connection to the file on the web. I'll place the cursor after InputStream, it looks like I didn't get my import statement and then press Ctrl + Spacebar and I'll make sure that I'm choosing the input string class from Java.I/O and there is the import.

Next I'll create an object which is an instance of BufferedInputStream. I'll type the beginning of the class and then press control space and Eclipse automatically auto completes it and I'll name that object buff for buffered and I'll instantiate it using the class' constructor method new BufferedInputStream and I'll pass in the stream object. The purpose of the BufferedInputStream is to do the same sort of looping that I did in the file, allowing me to read one or more bytes at a time as I loop.

Again, there is an indication of an error over on the left, don't worry about that I'll handle it later. Now we are ready to loop through the content of the file. I'm going to be reading the file this time one byte or one character at a time. In order to collect that data I'll create an object based on the StringBuilder class. I showed you how to use this class in an earlier video. The purpose of StringBuilder is to let you append content or insert content into a string without having to constantly rebuild the string object.

I'll name the StringBuilder object sp and I'll instantiate it with its constructor method. Now I'm ready to loop through the file and read it one byte at a time. I'll create a while loop, I'll type the word while and press Ctrl + Spacebar and choose while loop with condition. And I'll set the condition to the keyword true, that means I'm going to keep on looping until I call the break command and that will cause the flow to jump out of the loop. Each time through the loop, I'm going to read a single character from the stream.

The BufferedInputStream class has a method called read which returns a single byte. It will be returned as an integer initially, so I'll declare a variable named data and declare it as an int and I'll get its value from buf.read(). The rules are that as long as there is an available character to read in the stream the read command will return an integer value representing that character, but if it's gotten to the end of the stream, and the end of the file it will return a value of negative one. So I'll take a look at the value that I just received, I'll use an if command and this will be an 'if' statement and the condition will be data has a value of negative one, if that condition is true that means that I'm at the end of the document and so I'll break out of the while loop.

But otherwise which I'll put into the else block down here I'll append the value that was returned first converting it to a character using the syntax sp.append(data). But before I can pass that data value, I have to convert it to a character otherwise it'll be converted as a numeric. So I'll use casting syntax, I'll place the cursor before the data value and put in (Char). That means take the integer convert it to a character and then append it to the string.

I'll place the cursor after the while loop and finally I'll output the value that I've collected using system.out. println and I'll just output the value of the StringBuilder object. You could if you prefer convert the StringBuilder to a string, if you're going to keep it around in memory for a while. Now I've still got these errors up I have to deal with. Each of the errors indicates that there is an unhandled exception that could occur, as with all such conditions you deal with them by wrapping the code inside a TryCatch block.

So I'll select everything that I've coded inside the main method, I'll right click, I'll chose surround with TryCatch block. And Eclipse figures out which exceptions could occur and creates catch blocks for each of them. I will remove the TODO comments and my application should be complete. I'll Save and Run it and there is the result. The XML file is retrieved over the web and displayed in the Console. So again, this is one approach to retrieving files over the web and dealing with their content.

Once you have the content in memory, you could save it to the local file system, you could display it on the screen in whatever sort of application you're working in, or because it's structured XML, you could search for and extract its data. This sort of coding using the class library of the JDK will work in any Java environment, regardless of whether you're working with Console applications, Web applications, Android applications, it's all the same code because it's all Java.

Show transcript

This video is part of

Image for Java Essential Training
Java Essential Training

71 video lessons · 66805 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.