Java IO byte stream and character stream-reader and writer and implement file copy copy

Source: Internet
Author: User
Tags file copy

followed by a stream of bytes, the following main introduction character stream, character stream and byte stream difference and file copy copy. In the program, a character equals two bytes, and a Chinese character occupies two bytes (General Limited interview will ask: A char can save a Chinese character, the answer is, of course, a char and a Chinese character accounted for two bytes), the general use of byte stream if defined as odd number of length is, then stored Chinese characters will have garbled problem, Java provides two classes of reader and writer that specialize in manipulating character streams.

1 Writer character output stream

This class is an abstract class that needs to be implemented by its subclasses. Implements the Closeable,flushable, appendable three interfaces.

The following method:

Writer append (char c) adds the enactment character to the writer

void Close () Close Artesian

void Flush () refreshes the buffer of the stream change

void Write (char[] cbuf) writes a character array

void Write (char[] cbuf, int off, int len) writes a portion of the character array.

void write (int c) writes a single character

void write (String str) writes a string

void Write (String str, int off, int len) 写入字符串的某一部分。

 可以看出 Writer是对Char[] 和 String字符串操作,而OutputStream是对byte[]数组操作。Writer还可以向流中追加内容。

 下面是Writer的实例,使用其子类FileWriter实例化:

Package Andy.io.test;import Java.io.file;import Java.io.filewriter;import java.io.ioexception;import java.io.Writer ;/**   * @author zhang,tianyou   * version:2014-11-19 pm 4:59:24   *  *   */public class Writertest {/** * @ param args * @throws ioexception  */public static void Main (string[] args) throws IOException {//TODO auto-generated m Ethod stubfile file = new file ("D:" + File.separator + "test.txt"); Writer writer = Null;writer = new FileWriter (file, true);//The second argument is to append the content to the file string str = "Hello Andy!"; /Method One Writer.write (Str.tochararray ());//Method two//writer.write (str); Writer.close ();}}

2 Reader character input stream

 Reader也是抽象类,其实现了Closeable,readable interface.

The main methods are as follows:

void Close () close character input stream

int read () reads a single character.
int read (char[] cbuf) reads the characters into the array.
the abstract int read (char[] cbuf, int off, int len) reads the characters into a portion of the array.
int read (Charbuffer target) attempted to read a character into the specified character buffer.

The specific implementation is as follows:

Package Andy.io.test;import Java.io.file;import Java.io.filereader;import java.io.ioexception;import java.io.Reader ;/**   * @author zhang,tianyou   * version:2014-11-19 pm 5:11:02   *  *   */public class Readertest {/** * @ param args * @throws ioexception  */public static void Main (string[] args) throws IOException {//TODO auto-generated m Ethod stubfile file = new file ("D:" + File.separator + "test.txt"); Reader reader = Null;reader = new FileReader (file), char[] C = new char[(int) file.length ()];//method one//reader.read (c);//Method two in T temp = 0;int len = 0;while ((temp = Reader.read ())! =-1) {C[len] = (char) Temp;++len;} Reader.close (); System.out.println ("Content:" + new String (c));}}

3 The difference between a byte stream and a character stream

The use of byte stream and character stream is very similar, the byte stream is not used in the buffer (memory), it is the direct operation of the file itself, and the character stream is used in buffer to manipulate the file through buffer.

The character stream must use Clos () or flush () to output the stream in the buffer. and the byte stream does not turn off and can output normally.

The principle is as follows:

BYTE stream: Program------------------byte stream----------------------file

Character Stream: Program-------------------character stream----------------------cache-----------------------------File


Well, what's the best thing to do with it? : All files are carried out in bytes on the hard drive or in the process of transmission, including pictures, etc. are stored in bytes, and characters are only formed in memory, so the byte stream is generally used.


3 Implementing file Copy from A to B

Executing java FileCopy source file target file in cmd

Implementation ideas: 1 read the contents of the source file into memory and write it to the target file once.

2 does not read the contents of the source file, but uses the way of reading and writing the side.

We must adopt the second, if the file is read into memory at once, it will inevitably lead to memory overflow, affecting performance.


The specific implementation is as follows:

Package Andy.io.test;import Java.io.file;import Java.io.fileinputstream;import java.io.FileNotFoundException; Import Java.io.fileoutputstream;import java.io.ioexception;import Java.io.inputstream;import Java.io.OutputStream  ;/** * @author zhang,tianyou version:2014-11-19 pm 5:31:21 * */public class FileCopy {/** * @param args */public static void Main (string[] args) {//TODO auto-generated method stubif (Args.length! = 2) {//Determine if the file parameter is 2system.out.println ("File parameter is not That's right. "); System.out.println ("For example: Java FileCopy source file path destination file path"); System.exit (1);} File Srcfile = new file (Args[0]); File objfile = new file (Args[1]), if (!srcfile.exists ()) {System.out.println ("source file does not exist!) "); System.exit (1);} InputStream InputStream = Null;outputstream OutputStream = null;try {inputstream = new FileInputStream (srcfile);} catch (F Ilenotfoundexception e) {//TODO auto-generated catch Blocke.printstacktrace ();} try {outputstream = new FileOutputStream (objfile),} catch (FileNotFoundException e) {//TODO auto-generated catch blocKe.printstacktrace ();}  if (InputStream = null && outputstream! = null) {try {byte[] buff = new byte[1024];//read 1024 int len = 0;while (len = inputstream.read (buff))! =-1) {outputstream.write (buff, 0, Len);} Inputstream.close (); Outputstream.close ();} catch (IOException e) {e.printstacktrace ();}}}}




 

Java IO byte stream and character stream-reader and writer and implement file copy copy

Related Article

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.