How Java handles input/output--Text I/O (i)

Source: Internet
Author: User
File Class

The data stored in variables and objects is temporary, the program disappears when it terminates, and the data is stored in a file that allows data to be transmitted and used by other programs. In object-oriented program design, everything is object, so in order to allow the program to deal with files, you need to abstract a file into objects, in Java, get file attributes and delete, rename files and so on work by the file class to complete.

The file class contains many methods of getting file attributes, deleting files, and so on, but the file classdoes not contain methods for creating files and reading and writing file content , and using the file class requires the introduction of a package Java.io.File

In a file system, where each file is stored in a directory, a file class instance represents a directory/file, but it should be noted that creating a file instance does not create a document on the machine, regardless of whether the file exists, you can create an instance of any file name. You can call the exists () method to determine whether a file exists.

The file object encapsulates the properties of the files or paths, but does not include methods for creating files, reading and writing file data, and in order to complete I/O operations, you need to create objects using Java I/O classes to complete. You can use the scanner and PrintWriter classes to read and write the contents of a text file.

For example:

File file =new file ("Image/us.gif");

Creates an object file that represents the Image/us.gif file, and in subsequent operations, the file is represented by the object.

The directory separator in Windows is a backslash (), such as C:\book\hi.java, but in Java the backslash is a special character, so the Windows file directory should be represented as C:\\book\\hi.java. The file directory separator in Unix is a slash (/), such as/home/jing/hi.java. The Java Directory delimiter is also (/), and the statement new File ("Image/us.gif") works on Windows, UNIX, or any other system.

By using the file class we have abstracted a specific file into an object in the Java world, and then we need to create, write, and read it. For file input/output, Java provides a number of classes that can be divided into text I/O classes and binary I/O classes. This article introduces the text I/O, binary I/O open another article introduction

For text, the work of creating and writing is done by the output object--printwriter object, and the read work is done by the input object--scanner object. The input object (also called the input stream) reads the data stream from the file, and the output object (also called the output stream, Outputream) writes the data stream to the file. PrintWriter Write Data

Java.io.PrintWriter class instances can create a file and write data to a text file.

Common methods in PrintWriter:

Method Method Description
PrintWriter (File f) Creates a PrintWriter object for the specified file object F, which is specifically responsible for various write operations to file F. If the file does not exist, the file is created and, if it exists, the current contents of the file are discarded. Calling constructors may throw exceptions and need to be processed
PrintWriter (String fileName) Creates a PrintWriter object for the specified file name string
Print () Write to the file, depending on the parameters, there are various overloaded methods, write strings, double, int, and so on
println () Prints more than print () a row separator, which is defined by the system, and Windows is the \r\n,unix system \ n
Close () File must be closed using the close () method, no data written to be saved to file correctly

For example:

Import java.io.File
Import java.io.PrintWriter Public

class writedata{public
    static void Main (string[) args) {
        file F=new file ("A.txt");
        try {

            PrintWriter output=new printwriter (f);
            Output.print ("Hiworld");
            Output.close ();

        } catch (Exception e) {
            System.out.println ("Write file Error");
        }

The above program creates a file object for the A.txt file, creates a write object for the file object, writes "Hi Java" by writing the object, and closes the file.

Note:
1. Invoking the PrintWriter construction method may throw an I/O exception and pay attention to handling
2. You must use the close () method to turn off the file, or not to scanner read the data in the file that is written incorrectly.

The Java.util.Scanner class is used to read strings and basic type values, dividing input into useful information separated by whitespace characters, and creating scanner for files or system.in to read data from a file or keyboard. For example:

Scanner input=new Scanner (system.in)//read from keyboard, create system.in Scanner Scanner input=new for Scanner

(new File (filename)) ;//create scanner for a file

Note:
1. Invoking the scanner construct method may throw an I/O exception and pay attention to processing.
2. The input file does not have to be closed, but closing is a good habit. How scanner works

Nextbyte () are called token read methods, read delimiters-delimited tokens, default spaces, and you can use the Ustdelimiter (String regex) method to set a new separator pattern. Next () and Nextlint () will read a string, the next () method reads a delimiter-delimited string, nextlint () reads a row that ends with a row delimiter.

On the Windows platform, the line delimiter string is \ r \ n, on the UNIX platform \ n.
To get the line delimiter on a particular platform, use string lineseparator = System.getproperty ("Line.separator");
If you enter from the keyboard, each line ends with a carriage return, corresponding to the \ n character.

A token-reading method that first skips the separator and then reads a token that ends with a delimiter, and then the token is automatically converted to a type such as Byte,int, which does not need to be converted for the next () method. If the token and the expected type do not match, throw the run exception java.util.InputMismatchException.

The token read method does not read the delimiter after the token, and if nextline () is invoked after the token read method, the method reads the character starting with this delimiter to the end of the line delimiter, and the row delimiter is read, but the row delimiter is not nextline () Returns the part of a string.

For example:

A test.txt text file contains one row

12 345

After you finish executing the following code,

Scanner input=new Scanner (New File ("test.txt"));
int Intvalue=input.nextint ();
String Line=input.nextline ();

The Intvalue value is 12,line contains the characters ', ' 3 ', ' 4 ', ' 5 '

If the input is entered from the keyboard and is separated by a carriage return, enter 12 and enter, followed by 345, and then in the carriage return.

Scanner input=new Scanner (system.in);
int Intvalue=input.nextint ();
String Line=input.nextline ();

After execution, the value of Intvalue is 12,line is an empty string. Reason: The token Read method Nextint () reads 12 and then stops at the separator , where the separator is a row separator. Nextline () ends after the row delimiter is read, and then returns the string before the row delimiter, so line is empty because there are no characters before the row separator.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.