Section 39th: IO in Java

Source: Internet
Author: User

In Java IO

IOThe classification

First Division: input and output streams
Second Division: byte Stream and character stream
Third: node flow and processing flow

Node stream processing data, processing flow is based on the node flow processing.

IOThe focus in:

InputStreamOutputStreamFileInputStreamFileOutputStream
InputStream
int read(byte[] b,int off,int len)
OutputStream
void write(byte[] b,int off,int len)
// 第一步,导入类import java.io.*;class Demo { public static void main(String[] args){  // 声明输入流的引用  FileInputStream fis = null; // 声明输出流的引用 FileOutputStream fos = null;  try{   // 生成输入流的对象   fis = new FileInputStream("e:/from.txt");  // 生成代表输出流的对象  fos = new FileOutputSteam("e:/to.txt");  // 生成一个字节数组   byte[] buffer = new byte[100]; // 调用输入流对象的read方法  int temp = fis.read(buffer,0,buffer.length);  fos.write(buffer,0,temp);   for(int i=0; i<buffer.length; i++){    System.out.println(buffer[i]);   }  }catch(Exception e){   System.out.println(e);  } }}

IOis to read and write data, the flow of data is a Java program-based reference, attention to read methods and write methods.

Flow: In the Java input and output is through the flow of the class to achieve, Java provides a rich set of flow classes can be imported java.io , so that can complete the input and output, but also to achieve network operation and so on.

Hear the stream, is not very image of it? Flow is like a trend, when the program needs to read the data, it will open a stream to the data source, the data source can be files, memory, network connections, etc., need to write data, will also open a flow to the destination. Flow is like connecting the starting point to the end of the road.

input stream: source to program, that is, read, from the source of the input into the program, read the contents of a file read into the program.

output stream: output to the destination in the program, output stream, that is, write, one file to another file, from this side output to the other side.

In Java mid-stream: byte stream, character stream must be mastered

InputStreamOutputStreamReaderWriter

Focus early on Java content: InputStream and OutputStream , both of these are based on byte stream.

Character Stream: Reader andWriter

JavaFlow points in a language: text flow (character sequence) and binary stream

Input stream and output stream

InputStreamClasses are basic input stream classes, which are abstract classes that define methods in the class that are InputStream used to read read the data.

OutputStreamClasses are basic output classes, which are abstract classes that define methods in the class that are OutputStream write used to output data and write.

OutputStreamClass
Clear buffer:public void flush()
To close the output stream:public void close()

Other Highlights:

Java DataInputStream Classes and DataOutputStream classes, data input streams, and data output streams are provided in. Classes and classes are provided in the version, and JDK1.1 InputStreamReader OutputStreamWriter They are Reader subclasses of Writer the class, providing a conversion of a byte stream to a character stream.

Character Stream

BufferedReaderClasses and Classes BufferedWriter are Reader subclasses of classes and classes, and the Writer input and output buffers are provided.

File class

FileInputStreamClass is an input operation and is a file input stream class

import java.io.*;public class Demo{ public static void main(String[] args){  byte buffer[] = new byte[1024];  try{  // 创建FileInputStream类对象   FileInputStream fis = new FileInputStream("from.txt"); int temp = fis.read(buffer,0,buffer.length); String str=new String(buffer,0,temp); // 输出字符串内容 System.out.println(str);  }catch(Exception e){   System.out.println(e);  } }}

FileOutputStreamClass is the output class, and the same is true FileInputStream .

FileInputStreamClass, FileOutputStream class
DataInputStreamClass, DataOutputStream class
InputStreamClass, OutputStream class
BufferedReaderClass, BufferedWriter class

Talk aboutIO

//第一种:输入流输出流//第二种:字节流字符流//第三种:节点流处理流//FileInputStreamclass Test{ public static void main(String args[]){  FileInputStream fis = null;  try{  fis = new FileInputStream("e:/read.txt");  byte[] buffer = new byte[100];  fis.read(buffer,0,buffer.length);  for(int i = 0;i<buffer.length;i++){   System.out.println(buffer[i]);  }} catch(Exception e){ System.out.println(e);  } }}
class Test{ public static void main(String args[]){  FileInputStream fis = null;  FileOutputStream fos = null; try{  fis = new FileInputStream("e:/read.txt");  fos = new FileOutputStream("e:/write.txt");  byte[] buffer = new byte[100];  int temp = fis.read(buffer,0,buffer.length);  fos.write(buffer,0,temp);  }   catch(Exception e){    System.out.println(e);   }  }}
class Test{ public static void main(String args[]){  FileInputStream fis = null;  FileOutputStream fos = null;  try{   fis = new FileInputStream("e:/read.txt");   fos = new FileOutputStream("e:/write.txt");  byte[] buffer = new byte[1024];  while(true){   int temp = fis.read(buffer,o,buffer.length);   if(temp = -1){    break;   }   fos.write(buffer,0,temp);  }  }catch(Exception e){   System.out.println(e); }finally{  try{  fis.close();  fos.close(); }catch(Excepiton e){ System.out.println(e);  } }}}  
 //character stream public class Textchar public static void Main (String args[]) {FileReader FR = null;  FileWriter FW = NULL;  try{FR = new FileReader ("E:/read.txt");      FW = new FileWriter ("E:/write.txt");   char[] buffer = new CHAR[100];   int temp = Fr.read (buffer,0,buffer.length);    Fw.write (buffer,0,temp);   } catch (Exception e) {System.out.println (e);       }finally{try{fr.close ();       Fw.close ();    } catch (Excepiton e) {System.out.println (e); }  }}
 //filereader and bufferedreaderclass test{public static void Main (String args[]) {FileReader filereader = null;  BufferedReader BufferedReader = null;try{FileReader = new FileReader ("E:/read.txt");  BufferedReader = new BufferedReader (FileReader);   String line = null;   while (true) {line = Bufferedreader.readline ();   if (line = = null) {break;  } System.out.println (line);  }}catch (Exception e) {System.out.println (e);      } finally{try{bufferedreader.close ();    Filereader.close ();    } catch (Exception e) {System.out.println (e); }   }  }}
public class Test{ public static void main(String[] args) throws Exception{  //字节流 FileInputStream in = new FileInputStream("c:/read.txt"); FileOutStream out = new FileOutputStream("c:/write.txt"); byte[] buffer = new byte[1024];  int len;  while( (len = in.read(buffer)) != -1){  out.write(buffer,0,len);  }  in.close();  out.close();  //字符流  BufferedReader bf = new BufferedReader(new FileReader("c:/read.txt");  BufferedWriter bw = new BufferedWriter(new FileWriter("c:/write.txt"); String str; while( (str=bf.readLine()) != null ){  bw.write(str);  bw.newLine(); } bf.close(); bw.close();  }}

Byte stream: bytes InputStream input stream, OutputStream byte output stream
Characters stream: Reader character input stream, Writer character output stream
Data flow: Data DataInputStream input stream, DataOutputStream data output stream

File read/write

Objective
1 Several methods of mastering file reading and writing
2 FileOutputStream and FileInputStream the use of classes.
3 conversions between basic data types

The

Implements a file read after it is converted to uppercase and written to the destination file, where src refers to the source file, and des is the destination file directory.

public class Filedemo {//Create a folder public static void CreateFolder (String path) {file Folder=new file (path); if (folder.exists ()) {System.out.println ("folder already exists!        ");        }else{//Does not exist when going to create folder.mkdir (); }}//Create a file public static void CreateFile (String path,string filename) {file File=new file (path,filename)        ; The file determines if there is already an if (file.exists ()) {System.out.println ("File already exists!            ");        System.out.println (File.length ());            }else{try{file.createnewfile (); }catch (IOException e) {System.out.println ("File creation failed!            "); }}}//write file public static void write (string path,string filename) {try{string str= "0123            456789/nac "; String upstr = Str.touppercase ();//byte b[]=upstr.getbytes ();//FileOutputStream fos=new FileOutput            Stream (New File (Path,filename)); Fos.write (b);           Fos.close ();        }catch (FileNotFoundException e) {System.out.println ("file does not exist");        }catch (IOException e) {System.out.println ("Write file failed");            }}//read file public static void read (String path,string filename) {try{int length=0;                    String str= "";            byte buffer[]=new byte[10];                        FileInputStream fis=new FileInputStream (New File (Path,filename));            while ((length=fis.read (buffer, 0, buffer.length))!=-1) {str+=new String (buffer, 0, length);        } System.out.println (str);//Fis.close ();        }catch (FileNotFoundException e) {System.out.println ("file does not exist");        }catch (IOException e) {e.printstacktrace (); }}//public static void Filereadercopy (String src,string des) {try{filereader fr=new filereader (SRC)        ;        FileWriter fw=new FileWriter (DES);      Char C[]=new char[1024];  int len=0;        while ((Len=fr.read (c, 0, c.length))! =-1) {fw.write (c, 0, c.length);        } fw.close ();    Fr.close ();    } catch (FileNotFoundException e) {System.out.println ("file does not exist");    }catch (IOException e) {System.out.println ("Read and Write Failed");  }}//public static void Bufferedreadercopy (String src,string des) {try{BufferedReader br=new            BufferedReader (New FileReader (SRC));            BufferedWriter bw=new BufferedWriter (New FileWriter (DES));            String str= ""; while ((Str=br.readline ()) = null) {String upstr = Str.touppercase ();//Add Uppercase transform Bw.write (upst            R);//Bw.newline ();            } bw.close ();        Br.close ();        } catch (FileNotFoundException e) {System.out.println ("file exists");        }catch (IOException e) {System.out.println ("Read and Write Failed"); }}//Copy public static void copy (String src,string des){try{fileinputstream fis=new fileinputstream (SRC);            FileOutputStream fos=new FileOutputStream (DES);            int C;            while ((C=fis.read ())! =-1) {fos.write (c);            } fos.close ();        Fis.close ();        }catch (FileNotFoundException e) {System.out.println ("file does not exist");        }catch (IOException e) {System.out.println ("Read and Write Failed"); }}//Copy file public static void Copy1 (String src,string des) {try{fileinputstream fis=new Filein            Putstream (SRC);            FileOutputStream fos=new FileOutputStream (DES);            int C;            byte buff[]=new byte[1024];            while ((C=fis.read (buff,0,buff.length))! =-1) {fos.write (buff,0,c);            } fos.close ();        Fis.close ();        }catch (FileNotFoundException e) {System.out.println ("file does not exist");        }catch (IOException e) {System.out.println ("Read and Write Failed"); }    } public static void Main (string[] args) {//TODO auto-generated Method stub Filedemo.createfolder ("        C:/test ");        Filedemo.createfile ("C:/test", "1.txt");        Filedemo.write ("C:/test", "1.txt");        Filedemo.read ("C:/test", "1.txt");        Filedemo.read ("C:/test", "Filedemo.java");        Filedemo.bufferedreadercopy ("C:/test/filedemo.java", "C:/test/filedemo2.java");    Filedemo.copy1 ("C:/test/1.mp3", "C:/test/2.mp3"); }}
Read the file
//读文件public static void read(String path,String filename){ try{  int length = 0;  String str = "";  byte buffer[]=new byte[10];  FileInputStream fis=new FileInputStream(new File(path,filename));    while((length=fis.read(buffer,0,buffer.length))!=-1){     str+=new String(buffer,0,length);  }  System.out.println(str);  fis.close(); }catch(FileNotFoundException e){   System.out.println("文件不存在"); }catch(IOException e){  e.printStackTrace(); }}
Creation of files
public class FileDemo{ public static void createFolder(String path){  File folder = new File(path);  if(folder.exists()){   System.out.println("文件已存在!");  }else{    folder.mkdir(); }} public static void createFile(String path,String filename){  File file = new File(path,filename);  if(file.exists()){   System.out.println("文件已存在!");   System.out.println(file.length());  }else{   try{    file.createNewFile();  }catch(IOException e){   System.out.println("文件创建失败");  }  }}public static void main(String[] args){  FileDemo.createFolder("c:/test");  FileDemo.createFile("c:/test","1.txt");}}
Write a file
public static void write(String path,String filename){ try{  String str = "234455";   byte b[] = str.getBytes();   FileOutputStream fos =  new FileOutputStream(new File(path,filename));  fos.write(b); }catch(FileNotFoundException e){   System.out.println("文件不存在");  }catch(IOException e){   System.out.println("写文件失败");  }}
Read and write files

Focus:

File class Main functions: Create, read properties, write attributes, delete etc.

File read and write operations

FileClass
FileObject of the class

Used to obtain the information of the file itself, such as the directory, file length, file read and write permissions, etc., does not involve the file read and write operations.

constructor function
File(String filename)File(String directoryPath,String filename)File(File f,String filename)
Get the properties of a file
String getName()boolean canRead()boolean canWrite()long length()boolean isFile()等
Directory Operations
boolean mkdir():创建目录。String[] list():以字符串的形式返回目录下所有文件。File[] listFiles():以File对象形式返回目录下所有文件。
File operations
boolean createNewFile():创建一个新的文件。boolean delete():删除一个文件
The concept of flow

JavaThe input and output functions are implemented with the input and output stream classes.

java.ioThe package contains a large number of classes to complete the input and output stream.

Categories in Java streaming:

The movement direction of the flow can be divided into 输入流 输出流 two kinds.

The data type of the stream can be divided into 字节流 and 字符流 .

The input stream classes are InputStream subclasses of abstract classes (byte input streams) or abstract class Reader classes (character input streams).

The output stream classes are OutputStream subclasses of abstract classes (byte output streams) or abstract class Writer classes (character output streams).

Input stream

The input stream is used to read data, and the user can read the data from the input stream, but not write the data.

The input stream reads the data as follows:

(1) Open a stream.
such as: FileInputStream inputFile = new FileInputStream ("Data source");
(2) Read the information from the information source.
such as: inputFile.read() ;
(3) Close the stream.
such as: inputFile.close() ;

Output stream

The output stream is used to write data. Can only write, cannot read.

The process of writing data to the output stream is as follows:

(1) Open a stream.
such as: FileOutputStream outFile = new FileOutputStream ("Data source");
(2) Write the information to the destination.
such as: outFile.write(inputFile.read()) :
(3) Close the stream. Such as:
such as: outFile.close() ;

IO
    1. I/OTarget of the operation
    2. IOThe Classification method
    3. Ways to read files and write files
Targets for I/O operations

The goal is to read data from the data source and write the data to the data destination.

From one place input to the java program output to another place.

File and Data Flow

Write and read out data files, in Java the 输入/输出 form of data streams, the two forms of data flow are 16位字符 or8位字节

Operands of the data flow:

数据文件的读写线程间的数据传输网络间的数据传播

Read/write steps:
Import input/output package, import java.io.* Package
To create a file object

FileReader/FileWriterClass for read and write operations on text files
DataInputStream(for file read-out) and DataOutputStream read-write to (for file write) class files
FileInputStream(for file readout) and FileOutputStream objects (for file writes)

Close File

closefunction Close File

Properties of the File object

Create a file

boolean createNewFile();

Create subdirectories

boolean mkdir();boolean mkdirs();

Rename/move files

boolean renameTo(File dest);

deleting files

boolean delete();

Check if the file exists

boolean exists();

Check whether the file

boolean isFile();

Check if it is a folder

boolean isDirectory();

Query file length

long length();

For the rest of your life, with you.
Jian Suda tert-Niche
A handsome boy, good development habits, ability to think independently, initiative and good at communication
Jane Book Blog: https://www.jianshu.com/u/c785ece603d1

Conclusion
    • I will continue to explain the other knowledge in depth, I am interested to continue to focus on
    • A little gift to walk or like.

Section 39th: IO in Java

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.