Java File Operations Summary

Source: Internet
Author: User
Tags readline

Randomaccessfile use of related APIs

    pointer=0; 文件指针        写方法 raf.write(int) -->只写一个字节 后8位,同时指针指向下一个位置,准备再次写入        读方法 int b = raf.read()-->读一个字节        读写文件完成后一定要关闭
    public static void Testrandomaccessfile () throws IOException {file Demo=new file ("demo");        if (!demo.exists ()) Demo.mkdir ();        File File=new file (demo, "Raf.dat");        if (!file.exists ()) file.createnewfile ();        Randomaccessfile raf=new randomaccessfile (file, "RW");        Pointer position System.out.println (Raf.getfilepointer ());        Raf.write (' A ');//write only one byte of System.out.println (Raf.getfilepointer ());        Raf.write (' B ');        int i=0x7fffffff;        Write method can be written to only one byte at a time, if you want to write I will have to write 4 times raf.write (i>>>24);//high 8-bit raf.write (I>>>16);        Raf.write (I>>>8);        Raf.write (i);        System.out.println (Raf.getfilepointer ());        You can write an int raf.writeint (i) directly;        String s = "Medium";        Byte[] Gbk=s.getbytes ("GBK");        Raf.write (GBK);//write byte array System.out.println (Raf.length ());        The read file must move the pointer to the head raf.seek (0); Read once. Read the contents of a file into a byte array byte[] Buf=new byte[(int) raf.length ()];        Raf.read (BUF);        System.out.println (arrays.tostring (BUF));        for (byte b:buf) {System.out.println (integer.tohexstring (B&0XFF) + "");    } raf.close (); }

Writeint () method source code, each write a


Image.png

IO stream (input stream, output stream)
Byte stream, character stream
1. Byte stream
1) InputStream, OutputStream
InputStream abstracts the way the application reads data
OutputStream abstracts the way the application writes data
2) Eof=end read-1 reading to the end
3) Input Stream Basic method
int B=in.read (); Reads a byte unsigned padding to the lower eight bits of int. -1 is EOF
In.read (byte[] buf) reads data into a byte array buf
In.read (byte[] buf,int start,int size) reads data into byte array buf, starting at buf start position, storing data of size length
4) Basic method of output stream
Out.write (int b) writes out a byte to stream, B's low 8 bits
Out.write (byte[] buf) writes the BUF byte array to the stream
Out.write (byte[] buf,int start,int size)
5) FileInputStream---> specifically read the data on the file
6) FileOutputStream implements a method for writing byte data to a file
7) Dataoutputstream/datainputstream
The extension of convection function, can be more convenient to read Int,long, characters and other types of data
DataOutputStream
Writeint ()/writedouble ()/writeutf ()
DataOutputStream dos=new DataOutputStream (new FileOutputStream (file));
8) Bufferedinputstream&bufferedoutputstream
These two stream classes provide the IO with buffer operations, which are generally buffered when opening files for write or read operations, which improves IO performance

Putting input into a file from an application is equivalent to pouring a cylinder of water into another cylinder:
FileOutputStream--->write method partisans with a drop of water transfer to the past
DataOutputStream--->writexxx () method will be convenient, the equivalent of a scoop of a ladle transfer
Bufferedoutputstream--->write method is more convenient, the equivalent of a scoop of water first into the bucket, and then imported from the barrel into another cylinder

Using the In.read () method

    /*    读取指定文件内容,按照16进制输出到控制台    并且每输出10个byte换行     */    public static void printHex(String filename) throws IOException {        //把文件作为字节流进行读操作        FileInputStream in=new FileInputStream(filename);        int b;        int i=1;        while((b=in.read())!=-1){            if(b<=0xf) {                //单位数前面补0                System.out.print("0");            }            System.out.print(Integer.toHexString(b)+" ");//将整形b转换为16进制的字符串            if(i++%10==0)                System.out.println();        }        in.close();    }

Using In.read (byte[] buf, int start, int size)
Reads data into a byte array, returns the data size, loops out the byte array

 public static void Printhexbybytearray (String filename) throws ioexception{FileInputStream in=new FileInputStream (        filename);        Byte[] Buf=new byte[20*1024]; Bulk read bytes from in, put into the BUF byte array, starting at the No. 0 position,///Up to Buf.length returns the number of bytes read/* int bytes=in.read (buf,0, BUF.L        ENGTH);//Read all at once, indicating that the byte array is large enough int j=1; for (int i=0;i<bytes;i++) {if (buf[i]&0xff) >0&& (buf[i]&0xff) <=0xf) {Syst            Em.out.print ("0");            } System.out.print (Integer.tohexstring (buf[i]) + "");        if (j++%10==0) System.out.println ();        }*///Recycle BUF array to prevent the opening of the array space is not enough case int bytes=0;        int j=1; while ((Bytes=in.read (buf,0,buf.length))!=-1) {for (int i=0;i<bytes;i++) {//To avoid data type conversion errors, the high 24-bit                Clear 0 System.out.print (integer.tohexstring (Buf[i] & 0xff) + "");            if (j++%10==0) System.out.println ();  }      }    } 

Copying of files
If the file does not exist directly, if it exists, it is created after deletion. Append if append=true, does not exist
FileOutputStream out=new FileOutputStream ("Demo/out.dat");

   public static void copyFile(File srcFile,File destFile)throws IOException{        if(!srcFile.exists())            throw new IllegalArgumentException("文件"+srcFile+"不存在");        if(!srcFile.isFile())            throw new IllegalArgumentException(srcFile+"不是文件");        FileInputStream in=new FileInputStream(srcFile);        FileOutputStream out=new FileOutputStream(destFile);        byte[] buf=new byte[8*1024];        int b;        while((b=in.read(buf,0,buf.length))!=-1){            out.write(buf,0,b);            out.flush();//最好加上        }        in.close();        out.close();    }
 //Take advantage of buffered byte stream public static void Copytfilebybuffer (File srcfile,file destfile) throw        S ioexception{if (!srcfile.exists ()) throw new IllegalArgumentException ("file" +srcfile+ "does not exist");        if (!srcfile.isfile ()) throw new IllegalArgumentException (srcfile+ "is 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 (); }

2. Character Stream
1) encoding Problem
2) Understanding text and text Files
Java text (char) is a 16-bit unsigned integer, which is the Unicode encoding of the character (double-byte encoding)
file is a byte byte byte ... The data series
text file is a text (char) sequence that is serialized as a result of encoding scheme (UTF-8,UTF-16BE,GBK) to byte stored results
3) character Stream (reader writer)---> action is a text file
The processing of characters is processed one character at a time, the underlying implementation of the
character is still the basic byte sequence
character stream,
InputStreamReader completes a byte stream parsing to a char stream, parsing by encoding
OutputStreamWriter Provides a char stream to a byte stream, which is processed by encoding

//注意编码问题public class IsrAndOswDemo {    public static void main(String[] args) throws IOException {        FileInputStream in=new FileInputStream("G:\\11.txt");        InputStreamReader isr=new InputStreamReader(in,"utf-8");//默认项目的编码        FileOutputStream out=new FileOutputStream("G:\\12.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;        while((c=isr.read(buffer,0,buffer.length))!=-1){            String s=new String(buffer,0,c);            System.out.println(s);            osw.write(buffer,0,c);            osw.flush();        }        isr.close();        osw.close();    }}

Filereader/filewriter

public class FrAndFwDemo {    public static void main(String[] args) throws IOException {        FileReader fr=new FileReader("g:\\11.txt");        FileWriter fw=new FileWriter("g:\\13.txt");        char[] buffer=new char[2056];        int c;        while((c=fr.read(buffer,0,buffer.length))!=-1){            fw.write(buffer,0,c);            fw.flush();        }        fr.close();        fw.close();    }}

Filter for character streams
BufferedReader---> ReadLine read one line at a time
Bufferedwriter/printwriter---> Write a line

public class BrAndBwOrPwDemo {    public static void main(String[] args) throws IOException{        BufferedReader br=new BufferedReader(new InputStreamReader(new FileInputStream("g:\\11.txt")));       // BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(new FileOutputStream("g:\\123.txt")));        PrintWriter pw=new PrintWriter("g:\\1234.txt");        String line;        while((line=br.readLine())!=null){            System.out.println(line);            pw.println(line);            pw.flush();//            bw.write(line);//            //单独写出换行操作//            bw.newLine();//换行操作//            bw.flush();        }        pw.close();        br.close();//        bw.close();    }}

Welcome to join the Learning Exchange Group 569772982, we learn to communicate together.

Java File Operations Summary

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.