I. INTRODUCTION of IO
BYTE: Byte, a unit of data stored in a computer, a byte with 8 bits, is a very specific storage space
Characters: Symbols used by people, abstract meanings, such as ' 1 ' in ' a ', ' $ '
Character Set and encoding:
- What characters are there?
- Specifies whether each character is stored in one or more bytes, and which bytes are stored
IO is input and output, i.e. "read" and "write"
Based on data direction: input stream, output stream, according to processed data type: Byte stream, character stream
Second, byte input stream
Import Java.io.file;import Java.io.fileinputstream;import Java.io.ioexception;public class InputStreamTest {public static void Main (string[] args) {File file = new file ("Text.txt"); try {//1, create a file named Text file.createnewfile (); FileInputStream fis = new FileInputStream ("Text.txt"); Reads the next byte of data from the input stream, returns an int value of 0-255, reads the end of the -1//Fis.read (), or reads the data from the input stream into a byte array byte[] input = new Byte[1];fis.read (input); String str = new string (input); System.out.println (str);
Fis.close ();} catch (IOException e) {//TODO auto-generated catch Blocke.printstacktrace ();}}}
Conversion between String and Byte []
- byte [] strbyte = Str.getbytes ();
- String st = new String (byte);
Three, byte output stream
1 ImportJava.io.FileOutputStream;2 Importjava.io.IOException;3 4 Public classOutputstreamtest {5 6 Public Static voidMain (string[] args) {7 Try {8 //Open Input Stream9FileOutputStream fos =NewFileOutputStream ("Textw.txt");Ten One //the data to write AString str = "Write Data: 1234"; - byte[] out =str.getbytes (); - the //writes data to the specified file - Fos.write (out); - - //Close the stream + fos.close (); - +}Catch(IOException e) { A //TODO auto-generated Catch block at e.printstacktrace (); - } - } - -}
View CodeIv. implement file copy via byte stream
1 ImportJava.io.FileInputStream;2 Importjava.io.FileNotFoundException;3 ImportJava.io.FileOutputStream;4 Importjava.io.IOException;5 6 Public classCopyStream {7 8 Public Static voidMain (string[] args) {9 Try {Ten //Create an input/output stream, read data from a text.txt file, and store the read data in Textnew.txt OneFileInputStream FIS =NewFileInputStream ("Text.txt"); AFileOutputStream fos =NewFileOutputStream ("Textnew.txt"); - - //an array of stored data the byte[] Shuju =New byte[50]; - - while(Fis.read (shuju)! =-1) { - Fis.read (Shuju); + } - + //writes data from a byte array to the Textnew.txt A Fos.write (Shuju); at - fis.close (); - fos.close (); -}Catch(FileNotFoundException e) { - //TODO auto-generated Catch block - e.printstacktrace (); in}Catch(IOException e) { - //TODO auto-generated Catch block to e.printstacktrace (); + } - the } * $}
View Code
Java--io Flow