Java file I/O (java files input and output)

Source: Internet
Author: User

File Overview

I/o = Input/output, here it's Input to and Output from programs

Inputs can be From:keyboard Files ETC.

Output can be:screen Files ETC.

Advantages of file I/O

-permanent Copy

-output from one program can is input to another

-input can automated (rather than entered manually)

Streams

Stream:an object, either delivers data to its destination (screen, file, etc.) or the takes data from a source (keyb Oard, file, etc.) It acts as a buffer between the data source and destination

Input STREAM:A stream that provides input to a program e.g., System.in was an input stream

Output stream:a stream, accepts output from a program e.g., System.out was an output stream

Examples:System.out.println ("Hi") connects a program to the screen

Streams as a transmission tool during the transmission of electronic devices and programs

Binary vs. Text Files

All data and programs is ultimately just zeros and ones each digit can has one of the values (0 or 1),

Hence binary 1 byte = 8 bits

  Text files: the bits represent printable characters

One byte per character for ASCII, the most common code

  For example, Java source files is the text files is an any file created with a "text editor"

  Binary files: The bits represent other types of encoded information, such as executable instructions or numeric d Ata

Text files vs. Binary files

Numbe r:127 (decimal) decimal

Text file Three bytes: "1", "2", "7" ASCII (decimal): 49, 50, 55

ASCII (binary): 00110001, 00110010, 00110111

Binary file:one Byte (byte): 01111111-bytes (short): 00000000 01111111 four bytes (int): 00000000 00000000 000 00000 01111111

Buffering

Not Buffered:each byte was Read/written from/to disk as soon as possible "little" delay for each byte A disk operation per BYTE---higher overhead

Buffered:reading/writing in "chunks" Some delay for Some bytes,

e.g.: Assume 16-byte buffers

Reading:access the first 4 bytes, need to wait for all bytes is read from disk to memory

Writing:save the first 4 bytes, need to wait for all of bytes before Writing from memory to disk

A disk operation per a buffer of bytes---lower overhead

Java I/O

Standard IO:System.out.println ("a line"); To-send a line-to-the-standard output, i.e, the screen, unless-redirect standard output

public class Redirectsysout {//redirect output

public static void Main (string[] args) throws FileNotFoundException {//file to throw exception when not found

PrintStream stream1 = System.out; // Create a new print object

File afile=new file ("Sysout.log");

PrintStream stream2 = new PrintStream (new FileOutputStream (afile));

System.out.println ("1");

System.setout (STREAM2); The reset screen is output to the Stream2 object

System.out.println ("2");

System.setout (STREAM1);

System.out.println ("3");

}

}

Text File I/O

Important classes for text file output (to the file)

   1)FileWriter

   2) FileOutputStream

   3) BufferedWriter

   4)PrintWriter

Important classes for text file input (from thefile):

   1)FileReader

   2)BufferedReader

  FileWriter and filereader take file names as arguments.

  printwriter and BufferedReader provide useful methods for easier writing and reading.

The input and output of the TXT file, using FileReader and FileWriter.

Because the PrintWriter range is the largest, so it is most convenient to use?

Text File Output

To open a text file for Output:connect a text file to a stream for writing FileOutputStream

  Foutstream = new FileOutputStream ("OUT.txt");

  PrintWriter pwriter = new PrintWriter (foutstream);

Or:

  PrintWriter outputstream = new PrintWriter (New FileOutputStream ("OUT.txt"));

What happened is:create a PrintWriter object which uses FileOutputStream to open a text file FileOutputStream "connects" PrintWriter to a text file.

    

Exa

public static void Main (string[] args) {

PrintWriter outputstream = null;

try {

OutputStream = new PrintWriter (New FileOutputStream ("OUT.txt")); Open the file

for (int count = 1; count <= 3; count++)

Outputstream.println (count); Write the file

System.out.println ("... written to OUT.txt.");

Outputstream.close ();

} catch (FileNotFoundException e) {

System.out.println ("Error opening the file OUT.txt.") + e.getmessage ());

}

}

}

Overwriting a File

In the previous example:

-opening An output file creates a new file if it does not already exist

-If The file is existing,it would overwrite the file, i.e., data in the original file is lost

Because it was all overwrite before.

Appending to a Text File

To Add/append to a file instead of replacing it, use a different constructor for FileOutputStream:

    OutputStream = new PrintWriter (New FileOutputStream ("OUT.txt", true));

OutputStream = new PrintWriter (New FileOutputStream ("OUT.txt"));

for (int count = 1; count <=; count++)

Outputstream.println (count);

Outputstream.close ();

OutputStream = new PrintWriter (New FileOutputStream ("OUT.txt", true));

for (int count = 1; count <=; count++)

Outputstream.println (count);

Outputstream.close ();

Closing a File

After writing a file, you should close the FileOutputStream and the printwriter

  Fileoutputstream.close ();

  Outputstream.close ();

-why Close the file?

To make sure it's closed if a program ends abnormally (it could get damaged if it's left open) Flush the stream calling  Close () on a wrapper stream should close the child stream. e.g., if a printwriter is closed, the fileoutputstream it linked and is also closed.

-outputstream.close ();

Both the PrintWriter and fileoutputstream have been closed!!! Program is through the printwriter--"fileoutputstream contact TXT (for example), if you close the FileOutputStream directly disconnect the program and the file, it is equal to both closed.

Text File Input

To open a text file for Input:connect a text file to a stream for reading a BufferedReader object, which uses Filerea Der to open a text file FileReader "connects" BufferedReader to the text file

    FileReader s = new FileReader ("Input.txt");

    BufferedReader instream = new BufferedReader (s);

Pre

    BufferedReader instream = new BufferedReader (New FileReader ("Input.txt"));

try {

   FileReader fr=new FileReader ("Input.txt");

   BufferedReader InputStream = new BufferedReader (FR);

String line = null;

while ((line=inputstream. ReadLine ())!=null)//Check whether reached the end

System.out.println (line); Read a line from the file

    InputStream. Close ();

} catch (FileNotFoundException e) {

System.out.println ("File not Found.");

} catch (IOException e) {

System.out.println ("Error reading from File" + fileName);

}

StringTokenizer

There is methods to read a line and a character, but isn't just a single word

StringTokenizer:

Token:a block of (useful) text

Delimiter:is a character used to separate items of data

e.g., CSV files:comma-delimited

Create a StringTokenizer instance you can specify delimiters (the character or characters that separate words)

The default delimiters Are:space, tab, and newline

       StringTokenizer (String str, String Delim, Boolean returndelims)//str--the string to be separated delim--the Delimite RS Returndelims--whether return delimiters as tokens

Read an integer by using BufferedReader

No methods to read numbers directly read numbers as Strings and then convert them:

try{

String line =inputstream.readline ();

int value = Integer.parseint (line);

} catch (Java.lang.NumberFormatException e) {

...

} catch (IOException e) {...}

Creating Scanner Objects

We can create a Scanner object by invoking several different constructors.

Scanner (File Source)

Constructs a new Scanner that produces values scanned from the specified file.

Scanner (InputStream Source)

Constructs a new Scanner that produces values scanned from the specified input stream.

Scanner (String Source)

Constructs a new Scanner that produces values scanned from the specified string. ...

Example (read a line from keyboard):

Scanner sc = new Scanner (system.in);

Next Methods/hasnext Methods

Example:

  Scanner sc = new Scanner (system.in);

int I=sc.nextint ();

Scanner sc = new Scanner (system.in);

System.out.print ("Enter first int:");

while (Sc.hasnextint ()) {

int i = Sc.nextint ();

SYSTEM.OUT.PRINTLN ("you entered" + i);

System.out.print ("Enter another int:");

}

Delimiters in Scanner

Default delimiters are:space, tab, New line

Java file I/O (java files input and output)

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.