JAVA IO Topics

Source: Internet
Author: User

first look at a few common Encoding Method

public class Encodedemo{public static void Main (string[] agrs) throws ioexception{string s= "China abc"; byte[] byte1= S.getbytes (); The default is the project's UTF-8 encoding byte[] byte2=s.getbytes ("GBK");//display the specified encoding mode is gbkbyte[] byte3=s.getbytes ("utf-16be"); for (byte b:byte1) {/** * converts bytes to int in 16 binary display * The default is the project's code, where UTF-8 is used, the result is E4 B8 ad e5 9b BD 41 42 43 * Visible with UTF-8 encoding, Chinese occupies three bytes, English occupies one byte */system.out.print (integer.tohexstring (b & 0xff) + "");} System.out.println (); for (byte b:byte2) {/** * converts bytes to int as shown in 16 binary, high three byte 0 * display specified encoding is GBK, and the result is D6 D0 B9 FA 41 42 43 * Can be seen using GBK encoding, Chinese occupies three bytes, English occupies a Bytes */system.out.print (integer.tohexstring (b & 0xff) + ""); System.out.println (); for (byte b:byte3) {/** * Java is a double-byte encoding Utf-16be * Converts bytes to int as shown in 16 binary, high three byte 0 * Displays the specified encoding as UTF-16BE, resulting in 4e 2d, FD 0 41 0 42 0 43 * Can be seen using UTF-16BE encoding, Chinese occupies two bytes, English also occupies two bytes */system.out.print (integer.tohexstring (b & 0xff) + "");} System.out.println ();  /* The byte array is converted to a string and must be encoded in the same way as the previous conversion, otherwise garbled */string S1 = new String (byte1); System.out.println (S1); China ABC,Using the default project encoding format, string s2 = new string (BYTE2);  SYSTEM.OUT.PRINTLN (s2);//?й? Garbled, because Byte2 is GBK encoded, converted to a string using the default UTF-8 string s3 = new String (Byte2, "GBK"); System.out.println (S3);//China ABC, display specified GBK encoding, will not appear garbled}}

As can be seen from this example, the commonly used encoding method has UTF-8, Chinese character coding station Three bytes, the English letter code occupies 1 bytes;GBK encoding, Chinese occupies two bytes, the English letter occupies a byte;Java is a double-byte utf-16be encoding, which uses two bytes in both Chinese and English, and when the string and byte are converted by default, the encoding method specified by the project is used, and the bidirectional conversion is also noted. The encoding must be the same, otherwise it will appear garbled.


use of the file class :

The Java.io.File class is used to represent a file or directory that is used only to represent the information (name, size, and so on) of a file or directory and cannot be used for access to file content

public class Filedemo {public static void main (string[] args) {/* * understand several commonly used constructors */file file = new file ("f:\\ happy");//Note: path to use Double slash or back slash System.out.println (file); File File2 = new file ("F:\\ happy", "Happy 1.txt"); File File3 = new file (file2, "Happy 2.txt"), if (!file.exists ()) {/* * * If Directory does not exist, create directory, mkdirs () can be used to create multilevel directory * File.createnewfile () Used to create file */file.mkdir (); }else{file.delete ();} /* * Several commonly used API */system.out.println (File.isfile ()) for file classes; System.out.println (File.isdirectory ()); System.out.println (file); Print the path of the file System.out.println (File.getabsolutepath ());//The full path of the same print file System.out.println (File.getname ()); Print the name of the file or directory System.out.println (File.getparent ());//print the file or directory of the parent directory System.out.println (File.getparentfile ());}}

The above describes several ways that the file class creates objects and common APIs



A few commonly used operations on files or directories, such as filtering, traversal, etc.

/<span style= "font-family:arial, Helvetica, Sans-serif;" >/Some common operations for packaging file, such as filtering, traversing </span>
public class fileutil{/* * traverse all files and directories under directory */public static void ListDirectory (file dir) throws Ioexception{if (!dir.exists () {throw new IllegalArgumentException ("directory" +dir+ "does not Exist");} if (!dir.isdirectory ()) {throw new IllegalArgumentException (dir+ "is not a Directory");} /*string[] FileNames = Dir.list (); Returns the string array, the name of the direct child, without the contents of the subdirectory for (string string:filenames) {System.out.println (string);} */file[] files = dir.listfiles (); if (Files!=null && files.length>0) {for (File file:files) { System.out.println (file), if (File.isdirectory ())//recursive traversal {listdirectory (file);}}} }

randomaccessfile class : Provides access to the contents of a file, which can be read or written. It provides random access to the file and can access any location of the file

1> file Mode

Java file, on the hard disk is a byte byte byte ... Stored, is the collection of data

2> Open File

Open file has two modes "RW" read-write operation "R" read-only operation

Randomaccessfile RAF = new randomaccessfile (file, "WR"), Randomaccessfile random access is implemented by a file pointer, opening the default pointer position of the file Prointer =0, that is, at the beginning of the file. Read and write operations are accompanied by the movement of the pointer position.

3> Writing method

Raf.write (int),-----> write only one byte, and the pointer only wants the next position, ready to write again

4> Reading method

Raf.read ()----> write only one byte

5> files must be closed after reading and writing, or unexpected errors will occur.

public class Randomaccessfiledemo {public static void main (string[] args) throws Ioexception{file file = new File ("demo"); F (!file.exists ()) {file.createnewfile ();} Randomaccessfile RAF = new Randomaccessfile (file, "RW"); System.out.println (Raf.getfilepointer ()); Gets the position of the file pointer, 0raf.write (' A ');//writes only one byte System.out.println (Raf.getfilepointer ()); 1int i = 0x7fffffff;//maximum integer//write method, only one byte can be written at a time, write an int need to write 4 times raf.write (i>>24); Raf.write (i>>16); Raf.write (i>>8); Raf.write (i);//You can also write an int directly, the bottom of the time is also four write operations Raf.writeint (i); System.out.println (Raf.getfilepointer ()); String s= "China"; byte[] byte1 = s.getbytes ("GBK"); Raf.write (byte1); System.out.println (Raf.length ()); The length of the file 13//read the file must move the file pointer to the beginning of the file, you can also move to the specified location to read Raf.seek (0); byte[] buf = new byte[(int) raf.length ()];raf.read (BUF);// Bulk Read System.out.println (arrays.tostring (BUF));//output for (byte b:buf) {System.out.print (integer.tohexstring (b) in 16 binary mode &AMP;0XFF) + "");} Raf.close ();}}

Io Stream (input stream, output stream)

Byte stream :

1>

InputStream Abstracts the way the application reads the data and reads it into the program as input

OutputStream Abstracts the way the application writes data

2>

EOF =end Read-1 to the end of the file

3> input Stream Basic method

int b = In.read (); Reads a byte padding to int low eight bits

In.read (byte[] buf); Bulk reading of bytes into byte arrays

In.read (byte[] buf, int start, int size)

Basic method of 4> output stream

Out.write (int b)//write down eight bits to stream of int b

Out.write (byte[] b); Write out all bytes in the byte array

Out.write (byte[] B, int start, int size)//start with the following table, write a size byte

5> Concrete Implementation Class

FileInputStream ---> Specifically read data in Files

/* * Read the contents of the specified file in hexadecimal output to the console * Every 10 bytes read, * Single byte read, not suitable for large files, inefficient */public class ioutil{public static void Printhex (String filen AME) throws Ioexception{fileinputstream fis = new FileInputStream (filename); int b;int i=1;while ((B=fis.read ())!=-1)// Read Only one byte {if (B&LT;=0XF) System.out.print ("0") at a time, or 0 System.out.print (integer.tohexstring (b) + "") if only the fourth bit, if (i+ +%10 = = 0) {System.out.println ();}} Fis.close ();} /* * Bulk Read, large file size is very efficient * Common file read mode */public static void Printhexbybytearray (String filename) throws ioexception{ FileInputStream fis = new FileInputStream (filename), byte[] buffer = new byte[10*1024];/* * Bulk Read bytes from FIS, put into buf, start at No. 0 position , up to buffer.length bytes * Returns the number of bytes read * To prevent a file from being read at a time, use the while loop to read to the end of the file */int n;while ((n=fis.read (buffer, 0, buffer.length))!=-1) {int k=1;for (int i=0;i<n;i++) {if (buffer[i]<=0xf) System.out.print ("0"); System.out.print (integer.tohexstring (BUFFER[I]&AMP;0XFF) + ""); if (k++%10 = = 0) System.out.println ();}} System.out.println (); Fis.close ();} /* * Copy */public static void for file  CopyFile (file Srcfile,file destfile) throws Ioexception{if (!srcfile.exists ()) throw new IllegalArgumentException ("Original file "+srcfile+" does not exist "), if (!srcfile.isfile ()) throw new IllegalArgumentException (srcfile+" not a file "); FileInputStream in = new FileInputStream (srcfile); FileOutputStream out = new FileOutputStream (destfile); byte[] buf = new Byte[10*1024];int N;while ((N=in.read (buf, 0, BUF.L ength))!=-1) {out.write (buf, 0, N);}}


FileOutputStream ---> Inherited the OutputStream, which implements the method of writing byte data to the file .

public class FileOutputStreamDemo1 {public static void main (string[] args) throws ioexception{//if the file does not exist, the file is created if the file exists, Then re-create fileoutputstream fos = new FileOutputStream ("Demo.dat", true);/* * If the file does not exist, create the file, and if the file exists, write the data to the file in Append mode * FileOutputStream fos = new FileOutputStream ("Demo.dat", "true"); */fos.write (' A ');  Write a byte of string s = "China"; byte[] B = s.getbytes (); Fos.write (b); Write a byte array of fos.close ();} public static void  CopyFile (File srcfile,file destfile) throws Ioexception{if (!srcfile.exists ()) throw new IllegalArgumentException ("Original file" +srcfile+ "does not exist"), if (!srcfile.isfile ()) throw new IllegalArgumentException (srcfile+ " Not a document "); FileInputStream in = new FileInputStream (srcfile); FileOutputStream out = new FileOutputStream (destfile); byte[] buf = new Byte[10*1024];int N;while ((N=in.read (buf, 0, BUF.L ength)) (!=-1) {out.write (buf, 0, N);}}}

Datainputstrean and Dataoutputstrean are decorated with a single byte read operation in the bottom wrapper

                Out.writeint, Out.writeint ( -10); Out.writelong (10l); out.writedouble (1.11); Out.writeutf ("China"); Out.writechars ( "Chinese");
the corresponding read operation in the Datainputstrean


Buffered byte stream

bufferedinputstream and Bufferedoutputstream, provide the IO with buffer operations, generally open the file for write or read operations, will be buffered, this flow mode, Improves the performance of IO

public static void  Copyfilebuffer (File srcfile,file destfile) throws Ioexception{if (!srcfile.exists ()) throw new IllegalArgumentException ("Original file" +srcfile+ "does not exist"), if (!srcfile.isfile ()) throw new IllegalArgumentException (srcfile+ " Not a document "); Bufferedinputstream in = new Bufferedinputstream (new FileInputStream (srcfile)); Bufferedoutputstream out = new Bufferedoutputstream (new FileOutputStream (destfile)); int N;while ((N=in.read ())!=-1) { Out.write (n); Out.flush ();//must write}in.close (); Out.close ();}



You can also write a copyfilebybyte (), after comparison, in the larger file copy work, you create the byte[] array bulk read, the fastest, with a buffer in the way of the second, of course, it can be thought that the single byte copy is the slowest.


Character Stream

1> Understanding text and text files

Java literals (char) are 16-bit unsigned integers, which are Unicode encodings of characters (double-byte encoding)

file is a byte byte byte. Collection of sequences

A text file is a way for the text to be serialized as a byte stored in a coded manner

2> character Stream (Reader Writer)

The bottom of the character stream is still the basic byte sequence

Basic implementation of character stream----> manipulating text text files

INputstreamreadeR--to complete the byte stream parsing to a char stream, parsing by encoding

Outputstreamwrite ---completes the parsing of a char stream to a byte stream, as well as parsing by encoding

public class Firandfow {public static void main (string[] args) throws ioexception{fileinputstream in = new FileInputStream ( "C:\\unintall.log");/* can specify the encoding method, automatically recognize the newline */inputstreamreader reader = new InputStreamReader (in, "GBk"); FileOutputStream out = new FileOutputStream ("C:\\unintall1.log"); OutputStreamWriter writer = new OutputStreamWriter ( Out, "GBk"); int a;/* single character read while ((A = Reader.read ())!=-1) {System.out.print ((char) a);} *///Bulk Read char[] buffer = new Char[8*1024];while ((A=reader.read (buffer,0,buffer.length))!=-1) {writer.write (buffer, 0, a); Writer.flush ();//To add a refresh in order to output the contents of a character array to a file string s = new string (Buffer,0,a) in a timely manner; System.out.println (s);}}}

FileReader and FileWriter


As with InputStreamReader and OutputStreamWriter, the same way you read characters and character arrays, you just create objects in different ways

Datainputstrean
FileReader read = new FileReader (file);
FileWriter write = new FileWriter (file); The argument to the constructor is the file object

Note: This character stream operation has some flaws, we see in the construction method is not able to specify the encoding, so, the encoding of the read file must be the same as the encoding of the file, or there will be garbled


Filter for character streams

BufferedReader and BufferedWriter PrintWriter
The advantage is that the file can be read in the behavior unit

public class Bufferreaderwriter{public static void Main (string[] args) throws Ioexception{bufferedreader reader = new Buff Eredreader (New InputStreamReader (New FileInputStream ("C:\\unintall.log"), "GBK"));    BufferedWriter writer = new BufferedWriter (new OutputStreamWriter (New FileOutputStream ("C:\\unintall1.log"));    PrintWriter pwriter = new PrintWriter ("C:\\unintall1.log");    String Line;    /* While    (lines = Reader.readline ()) = null)    {    writer.write (line);//does not recognize newline    writer.newline ();//Manual line wrapping    Writer.flush ();    System.out.println (line);    }     */* * Because BufferedWriter creates objects that are more complex and does not recognize line breaks, use PrintWriter instead of *     /while (lines    = Reader.readline ()) ! = null)    {    pwriter.println (line);//Use this method to wrap    Pwriter.flush ();    System.out.println (line);}}}    

The above is the basic class of javaio and common operations, we can refer to this article for the other IO classes in the API to expand learning



Datainputstrean

JAVA IO Topics

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.