Java IO streaming File transfer base _java

Source: Internet
Author: User
Tags file copy flush mkdir

One, encoding of files

Package Com.study.io;  /** * Test File Encoding */public class Encodedemo {/** * @param args * @throws Exception/public static void Main (string[) args) Throws Exception {string s= "learn abc"; byte[] bytes1=s.getbytes ()//This is to convert a string into a character array, which is converted into a sequence of bytes using the project default encoding (here is UTF-8) for ( byte b:bytes1) {//bytes (converted to int) display System.out.print in 16 (integer.tohexstring (b & 0xff) + "");//&
0xFF is to remove the front 24 0 and leave only the rear eight-bit} System.out.println (); /*utf-8 encoding in Chinese occupies 3 bytes, English occupies 1 bytes/byte[] Bytes2 = s.getbytes ("Utf-8");//There will be an anomaly display, and we'll throw this exception for (byte b:bytes2) {System.
Out.print (integer.tohexstring (b & 0xff) + "");}
System.out.println (); /*GBK encoding Chinese occupies 2 bytes, English occupies 1 bytes/byte[] Bytes3 = s.getbytes ("GBK");//There will be an anomaly display, we'll throw this exception for (byte b:bytes3) {SYSTEM.OUT.P
Rint (integer.tohexstring (b & 0xff) + "");}
System.out.println (); /*UTF-16BE encoding Chinese occupies 2 bytes, English occupies 2 bytes/byte[] Bytes4 = s.getbytes ("Utf-16be");//There will be an anomaly display, we'll throw this exception for (byte b:bytes4) {Sy
Stem.out.print (integer.tohexstring (b & 0xff) + "");} System.out.println ();
* * When your byte sequence is some kind of encoding, this time want to turn the byte sequence into a string, also need to use this encoding, otherwise will appear garbled * * * * string Str1=new string (BYTES4);//This will use the project default encoding to convert, may appear garbled
System.out.println (STR1);
To convert string Str2=new string (bytes4, "utf-16be") using the encoding of the byte sequence;
System.out.println (STR2); }
}

Analysis:

* 1. Explanation of "& 0xFF":
* 0xFF means 16 (decimal is 255), expressed as binary is "11111111".
* Then the & symbol is the number of digits to the (same as 1 of the time to return 1, otherwise return 0)

* 2. Byte byte and int type conversions:
* Integer.tohexstring (b & 0xff) This is where the byte type B and 0xFF are first calculated, and then the integer.tohexstring gets the hexadecimal string
* You can see the B & 0xFF operation is still an int, so why and 0xFF to do with the operation? Direct integer.tohexstring (b); Will it not be possible to convert the byte to int? The answer is No.
* The reason is: the 1.byte size of 8bits and the size of the int is 32bits;2.java binary is the complement form
* integer.tohexstring parameter is int, if not &0xff, then when a byte is converted to int, because int is 32 bits, and byte is only 8 digits, then the complement ...
* So a byte and a 0xff session first converts that byte into a plastic operation, so that the high 24 bits in the result are always cleared 0, so the result is always what we want.

* 3.utf-8 Code: Chinese occupies 3 bytes, English occupies 1 bytes
* GBK code: Chinese occupies 2 bytes, English occupies 1 bytes
* Java with Double-byte encoding (that is, one character in Java is two bytes) is UTF-16BE encoding. Chinese occupies 2 bytes, English occupies 2 bytes
*
* 4. When your byte sequence is some kind of encoding, this time you want to turn the byte sequence into a string, you need to use this encoding, otherwise there will be garbled

* 5. A text file is a sequence of bytes. Can be any encoded sequence of bytes.
* If we create a text file directly on a Chinese machine, then the file only knows the ANSI encoding (for example, creating a text file directly on the computer)

II, use of the file class

Package Com.study.io;
Import Java.io.File; /** * The use of the * File class/public class Filedemo {/*java.io.file class indicates that the file or directory files class is used only to represent information about a file or directory (name, size, etc.) and cannot be used for access to file content. /public static void main (string[] args) {file File=new file ("d:\\111")//The specified directory when creating the file object requires a double slash because "\" is an escape character/*
The middle separator of the directory can be either a double slash or a backslash, or you can use File.separator to set the separator///File File1=new file ("D:" +file.separator); System.out.println (File.exists ());//exists () to determine if the file or folder exists if (!file.exists ()) {//If the file does not exist File.mkdir ();// Create a folder mkdir (), and mkdirs () create a multilevel directory}else{file.delete () or delete a file or folder}//Determine if it is a directory isdirectory, if the directory returns True,
Returns False System.out.println (File.isdirectory ()) If it is not a directory or directory does not exist;
Judge whether it is a file Isfile System.out.println (File.isfile ());
File File2=new file ("d:\\222", "123.txt");
Commonly used API:System.out.println (file);//Print the contents of file.tostring () System.out.println (File.getabsolutepath ()); Get absolute path
System.out.println (File.getname ());//Get File name System.out.println (File2.getname ()); System.out.println (File.getparent ());//Get Parent absolute path System.out.println (File2.getparentfile (). GetabsolutEpath ()); }
}

Run Result:

Description

Java.iO.File class represents a file or directory

The file class is used only to represent information about a file or directory (name, size, and so on) and cannot be used for access to file content.

Common APIs:

1. Create a File object: File File=new file (String path); Note: File.seperater (); Get the system separator, such as: "\".
2.boolean file.exists ();
3.file.mkdir (); or file.mkdirs (); Create a directory or multilevel directory.
4.file.isdirectory () to determine whether the directory
File.isfile () to determine if it is a file.
5.file.delete (), deleting files or directories.
6.file.createnewfile (), creating a new file.
7.file.getname () Gets the file name or the directory absolute path.
8.file.getabsolutepath () Gets the absolute path.
9.file.getparent (); Gets the parent absolute path.

1, traverse the directory

 package com.study.io; import java.io.File; import java.io.IOException;/** * File Tool class * column Out of the common operations of the file class, such as: filtering, traversal and other operations/public class FileUtils {/** * lists all files in the specified directory (including its subdirectories) * @param dir * @throws ioexception * * * publi The C static void ListDirectory (file dir) throws ioexception{if (!dir.exists ()) {//exists () method is used to determine whether a file or directory exists throw new
IllegalArgumentException ("Directory:" +dir+ "does not exist"); The IF (!dir.isdirectory ()) {//isdirectory () method is used to determine whether the object of the file class is a directory throw new IllegalArgumentException (dir+ "not a Directory"); string[] FileNames = Dir.list (); the//list () method lists subdirectories and files in the current directory (directly the name of the subdirectory, not containing the contents of the subdirectory), and returns a string array for (string string: FileNames) {System.out.println (string);} ///If you want to iterate through the contents of the subdirectory, you need to construct a file object to do the recursive operation, file provides the API file[to return directly to the file object] Listfiles = Dir.listfiles (), or a direct subdirectory (file) of the abstract if ( Listfiles!=null && listfiles.length >0) {for (file file:listfiles) {/*system.out.println (file); */if (file.i Sdirectory ()) {//recursive listdirectory (file);}
else{System.out.println (file);} }
}
}

Test class:

public class Fileutilstest {public
static void Main (string[] args) throws IOException {
fileutils.listdirectory (New File ("D:\\iostudy"));
}

Run Result:

Third, the use of Randomaccessfile class

Randomaccessfile:java provides access to the contents of a file, either by reading a file or by writing a file.

Randomaccessfile supports random access to files and can access any location in the file.

Note the Java file model:

Run Result:

1
12
[65, 66, 127,-1,-1,-1, 127,-1,-1,-1,-42,-48]
7f
Ff
Ff
Ff
7f
Ff
Ff
Ff
D6
D0

Four, Byte stream (FileInputStream, FileOutputStream)

IO streams can be divided into input and output streams.

This can be divided into byte stream and character streams.

code example:

Package Com.study.io;
Import Java.io.BufferedInputStream;
Import Java.io.BufferedOutputStream;
Import Java.io.File;
Import Java.io.FileInputStream;
Import Java.io.FileOutputStream;
Import java.io.IOException; /** * IO Tool class *❤ file input/output stream: * Fileinputstream--> specifically implemented to read data on the file * Fileoutputstream--> implemented the method of writing byte data to the file *❤ data input and output stream: * Outputstream/datainputstream: For the expansion of the "flow" feature, you can read more aspects of Int,long, characters, and other types of data * DataOutputStream Writeint ()/writedouble ()/ writeUTF () *❤ byte buffer stream: * Bufferedinputstream & Bufferedoutputstream * These two stream class bit IO provide a buffer operation, which is usually buffered when the file is opened for write or read operations.
This flow pattern improves IO performance * For example: putting input into a file from an application is equivalent to pouring one cylinder of water into another: FileOutputStream--->write () method is equivalent to "transfer" a drop of water over the past Dataoutputstream-->writexxx () method will be more convenient, equivalent to a ladle of water "transfer" Past Bufferedoutputstream--->write method more convenient, The equivalent of a ladle into the bucket (that is, the buffer), and then poured into another cylinder from the bucket, the performance increased/public class Ioutil {/** * Read the specified file content, in accordance with the 16 output to the console * and each output 10 byte line * @param filen AME * Single byte read is not suitable for large files, large file efficiency is very low * * public static void Printhex (String fileName) throws ioexception{//file as a byte stream operation Fileinputstr EAM IN=new FileInputStream (fileName);
int b;
int i=1; 
while ((B=in.read ())!=-1) {/* 0xFF replaced by 2 is 8 1, so with the words, in fact, is to take the character of the low 8 bits. * OXF is 15, the number less than 15 will be converted into a 16 number, * Your code would like to be a fixed two 16, so when only one will be generated to add a 0*/if (b <= 0xf) {//number of units before the 0 System.out.print ("0");}/
/integer.tohexstring (b) converts integer b to a string System.out.print (integer.tohexstring (b) + "") in the 16 binary notation;
if (i++%10==0) {System.out.println ();}} In.close ()//file read and write must be closed after the/** * bulk read, high efficiency for large files, but also our most common way to read the file * @param fileName * @throws ioexception * * public static void Printhexbybytearray (String fileName) throws ioexception{FileInputStream in = new FileInputStream (fileName); byte[]
BUF = new byte[8 * 1024]; /* Bulk Read bytes from in, put into buf this byte array, * Starting from No. 0 position, the maximum number of Buf.length * returned is read bytes//*int bytes = In.read (buf,0,buf.length); 
Read all at once, indicating that the byte array is large enough int j = 1;
for (int i = 0; i < bytes;i++) {System.out.print (integer.tohexstring (buf[i) & 0xff) + ""); if (j++%10==0) {System.out.println ();}}
*/int bytes = 0;
int j = 1; while ((bytes = In.read (buf,0,buf.length))!=-1) {for (int i = 0;
I < bytes;i++) {System.out.print (integer.tohexstring (buf[i) & 0xff) + "");
/** * & 0xff:byte type 8 bits, int type 32 bits, in order to avoid data conversion errors, through the &0xff will be high 24-bit clear 0/if (j++%10==0) {System.out.println ();}}
} in.close (); /** * file copy, byte bulk read * @param srcfile * @param destfile * @throws ioexception/public static void CopyFile (file srcfile,
File destfile) throws IOException {if (!srcfile.exists ()) {throw new IllegalArgumentException ("Files:" + Srcfile + "does not exist");
} if (!srcfile.isfile ()) {throw new IllegalArgumentException (Srcfile + "not file");}
FileInputStream in = new FileInputStream (srcfile); FileOutputStream out = new FileOutputStream (destfile);//If the file does not exist, it is created directly, if it exists, delete after byte[] buf = new BYTE[8 * 1024];//Bulk Read-write int
b while ((b = in.read (buf, 0, Buf.length))!=-1) {//read (buf,0,buf.length) with the parameter read returns the total length of the byte; when all is read, the return is -1; Out.write (buf
, 0, B);
Out.flush ();//Preferably add} in.close ();
Out.close (); /** * Copies of files, using buffered byte streams * @param srcfile * @param destfile * @throws ioexception/public static void CopyFileBybuffer (file Srcfile,file destfile) throws ioexception{if (!srcfile.exists ()) {throw new IllegalArgumentException ("File
: "+srcfile+" does not exist);
} if (!srcfile.isfile ()) {throw new IllegalArgumentException (srcfile+ "not a file");
Bufferedinputstream bis = new Bufferedinputstream (new FileInputStream (srcfile));
Bufferedoutputstream BOS = new Bufferedoutputstream (new FileOutputStream (DestFile));
int C;
while ((c = bis.read ())!=-1) {bos.write (c); Bos.flush ();//Flush Buffer} bis.close ();
Bos.close (); /** * single-byte, file copy without buffering * @param srcfile * @param destfile * @throws ioexception/public static void Copyfilebybyte (file Srcfile,file destfile) throws ioexception{if (!srcfile.exists ()) {throw new IllegalArgumentException ("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);
int C; while ((c = in.read ())!=-1) {//read () reads with no parameters the read byte content; When all is read, the return is -1; Out.write (c);
Out.flush ();
} in.close ();
Out.close (); }
}

Test class:

Package Com.study.io;
Import Java.io.File;
Import java.io.IOException;
Import Org.junit.Test; public class Ioutiltest {@Test public void Testprinthex () {try {Ioutil.printhex ("D:\\javaio\\fileutils.java");} catch (IOException e)
{E.printstacktrace ();} @Test public void Testprinthexbybytearray () {try {long start = System.currenttimemillis ();/current time with Coordinated Universal Day January 1, 1970
Night time lag (measured in milliseconds)//ioutil.printhexbybytearray ("E:\\javaio\\fileutils.java");
Ioutil.printhex ("E:\\javaio\\1.mp3");
Ioutil.printhexbybytearray ("E:\\javaio\\1.mp3");
System.out.println ();
Long end = System.currenttimemillis ();
System.out.println (End-start);
catch (IOException e) {e.printstacktrace ();}} @Test public void Testcopyfile () {try {ioutil.copyfile) (new file ("D:\\javaio\\1.txt"), New file ("D:\\javaio\\1copy.txt"
));
catch (IOException e) {e.printstacktrace ();}} @Test public void Testcopyfilebybuffer () {try {long start = System.currenttimemillis ();/*ioutil.copyfilebybyte (New File ("E:\\javaio\\1.mp3 "), New file (" E:\\javaio\\2.mp3 ")), */////20,000 MS/*ioutil.copyfilebybuffer (new file (" E:\\javaio\\1.mp3 "), new file ("E:\\javaio\\3.mp3")); /More than 10,000 MS/Ioutil.copyfile (new file ("E:\\javaio\\1.mp3"), New file ("E:\\javaio\\4.mp3");//7 millisecond long end =
System.currenttimemillis ();
System.out.println (End-start); 
catch (IOException e) {e.printstacktrace ();} }
}

Five, character streams

 package com.study.io; import java.io.FileInputStream; Import Java.io.FileOutputStream
;
Import java.io.IOException;
Import Java.io.InputStreamReader;
Import Java.io.OutputStreamWriter; public class Israndoswdemo {public static void main (string[] args) throws IOException {FileInputStream in = new FileInput
Stream ("E:\\javaio\\utf8.txt"); InputStreamReader ISR = new InputStreamReader (in, "utf-8")//Default item encoding, operation, encoding format to write the file itself fileoutputstream out = new
FileOutputStream ("E:\\javaio\\utf81.txt");
OutputStreamWriter OSW = new OutputStreamWriter (out, "utf-8");
/*int C; while ((c = isr.read ())!=-1) {System.out.print ((char) c);}
* * char[] buffer = new char[8*1024];
int C; /* Bulk read, put in buffer this character array, starting from No. 0 position, put up buffer.length the number of characters to be read/while ((c = Isr.read (buffer,0,buffer.length))!=-1
{String s = new string (BUFFER,0,C);
System.out.print (s);
Osw.write (BUFFER,0,C);
Osw.flush ();
} isr.close ();
Osw.close (); }
}

File read-write stream of character streams (Filereader/filewriter)

Filters for character streams

VI. serialization and deserialization of objects

Example:

Attention:

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.