开发者

What's the difference between File and FileLoader in Java?

开发者 https://www.devze.com 2023-03-16 14:50 出处:网络
So I have the following code where I should read a Text File (This is just the Main Class): import gui.MenuWindow;

So I have the following code where I should read a Text File (This is just the Main Class):

import gui.MenuWindow;
import java.io.IOException;
import javax.swing.JOptionPane;

public class Assessor {

    public static void main(String args[]) throws IOException {

        FileLoader file = new FileLoader("Example.txt");
        try{
            new MenuWindow(file.loader());
        } catch(Exception exc) {
            JOptionPane.showMessageDialog(null, "Error Reading File");
        }
    }
}

Then I'd have to load the Text into a ListBox using Swing. The thing is that I've found this new code to read a Text File:

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.IOException;

public class ReadTextFileExample {
    public static void main(String[] args) {
        File file = new File("test.txt");
        StringBuffer contents = new StringBuffer();
        BufferedReader reader = null;

        try {
            reader = new BufferedReader(new FileReader(file));
            String text = null;

            // repeat until all lines is read
            while ((text = reader.readLine()) != null) {
                contents.append(text)
                    .append(System.getProperty(
                        "line.separator"));
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOExcep开发者_JAVA技巧tion e) {
                e.printStackTrace();
            }
        }

        // show file contents here
        System.out.println(contents.toString());
    }
}

So I'd like to know what is the difference between the following two lines:

FileLoader file = new FileLoader("Example.txt"); //First Code

File file = new File("test.txt"); //Second Code

And... What's the StringBuffer and BufferedReader used to? Thanks!


So I'd like to know what is the difference between the following two lines:

FileLoader file = new FileLoader("Example.txt"); //First Code

File file = new File("test.txt"); //Second Code

The first creates a java.io.FileLoader which Andreas discusses. Since the javadoc says "The constructors of this class assume that the default character encoding and the default byte-buffer size are appropriate", it should never be used.

The second creates a java.io.File which is just a file path with some utility methods that can be used to read directory trees, delete, create, and move files, etc., or it can be used with FileInputStream and other classes to actually access the file contents.

And... What's the StringBuffer and BufferedReader used to? Thanks!

The StringBuffer is used to collect the contents of the file.

The BufferedReader is used to speed up reading of the file. Instead of reading one character at a time, the BufferedReader batches reads using an internal buffer.


This is an exemplary question about learning Java SE, especially regarding the java.io package. I was a bit puzzled in the beginning, but now I am quite sure that you want to compare the FileReader to the File class, which both belong to the same package java.io.

  1. File in the Java SE API:
    "An abstract representation of file and directory pathnames."
    In other words, it is there to handle files and directories on the file system within Java. Since Java is an object-oriented language, they made a class for it. Files, i.e. binary and text files, share some attributes in common with directories, as there are: absolute, canonical path and simple name, etc.
    Of course, File is one of the base classes in the java.io package and many classes like FileReader make use of it for object construction.

  2. FileReader:
    "Convenience class for reading character files."
    It comes with a handy constructor that takes a file name or file path as a String. Originally, it was meant to be constructed by a File instance. A Reader instance in general is practical to read text files, in contrast to InputStream, which is used to read binary files. A Reader instance in general is connected to a character set, e.g. "UTF-8" to translate byte to character streams.

Please also have a look at the excellent Java Tutorials provided by Oracle.

I hope the difference between File and FileReader becomes a little clearer. Especially note that there is no I/O, when you instantiate a File instance. To answer your question, the interconnection of the two classes would be:

File file = new File("test.txt"); // 1) Instaniate the file

Reader reader = new FileReader(file); // 2) Instantiate the Reader using the File instance

When you wrap a BufferedReader around a Reader instance, you can read the text file linewise, as:

BufferedReader bufferedReader = new BufferedReader(reader); // 3) Get a "buffered reader" to have access line by line.

StringBuffer comes in, when you want to chain a large number of String objects, since String objects is immutable and string operations like

String s1 = "Star ";
String s2 = "Wars";
s1 = s1 + s2;

are very costly, especially in loops, since at every addition a new String object (left side result) is created, with practically no size limits, apart from the reserved Java VM heap space.

Let me point out that you should better use the StringBuilder class, which is even faster, and is the unsynchronized counter-part of StringBuffer, introduced in the Java 5 release. The feature that StringBuffer is guaranteed to be synchronized among different Thread's is hardly ever used. I never came across it in my whole life as Java programmer.

0

精彩评论

暂无评论...
验证码 换一张
取 消