Turn! JAVA file read and write operation __java

Source: Internet
Author: User
Tags ming readline stub
file (memory)--Input stream--> "program"--Output stream-->file (memory)


When we read and write text files, it is very convenient to use reader, such as Filereader,inputstreamreader and BufferedReader. One of the most important classes is InputStreamReader, which is a bridge between bytes converted to characters. You can specify the encoding in the constructor, and the default encoding of the underlying operating system, such as GBK, will be used if unspecified. Read files using filereader: [Java] view plain copy print?        FileReader FR = new FileReader ("Ming.txt");        int ch = 0; while (ch = fr.read ())!=-1) {

FileReader FR = new FileReader ("Ming.txt");  

int ch = 0;  

while (ch = fr.read ())!=-1) 

  {   
[Java]View Plain copy print? System.out.print ((char) ch);
     System.out.print ((char) ch);   
[Java]View Plain copy print? }
  } 

where the Read () method returns the next character read. Of course you can also use Read (char[] ch,int off,int length) This is similar to when processing binary files.

In fact, the methods in FileReader are inherited from the InputStreamReader. Read () method is relatively good time, if in order to improve efficiency we can use BufferedReader to packaging reader, so as to improve the speed of reading, we can read the text on one line, using the ReadLine () method.

BufferedReader br = new BufferedReader (new InputStreamReader) (New FileInputStream ("Ming.txt"));
String data = null;
while (data = Br.readline ())!=null)
{
SYSTEM.OUT.PRINTLN (data);
}

Understanding the FileReader operation using FileWriter to write a file is simple, here do not repeat.

Eg. My comprehensive Example

Testfile:

[Java] View Plain copy print? import java.io.file;   import java.io.fileinputstream;   import  java.io.filenotfoundexception;   import java.io.fileoutputstream;   import  java.io.ioexception;   import java.io.inputstreamreader;      public  class testfile {       /**       * @ param args       */       public static  void main (String[] args)  {           //  TODO Auto-generated method stub            // file (memory)--Input stream--> "program"--Output stream-->file (memory)             file file = new file ("D:/temp",  "Addfile.txt");      & nbsp;    try {                file.createnewfile (); //  Create files             } catch  (ioexception e)  {                // TODO Auto-generated catch block                e.printstacktrace ();            }              //   Write content to file (output stream)            String str =  " Dear little Pumpkin. ";           byte bt[] = new byte[1024];            bt = str.getbytes ();            try {                fileoutputstream in = new fileoutputstream (file);                try {                    in.write (bt, 0, bt.length);                     In.close ();                    // boolean success=true;                    // system.out.println ("Write file succeeded");                } catch  (ioexception e)  {                    // todo auto-generated  catch block                    e.printstacktrace ();                }           } catch  ( Filenotfoundexception e)  {                // TODO Auto-generated catch block                e.printstacktrace ();            }           try {                //  Read File contents   (input stream)           &nBsp;     fileinputstream out = new fileinputstream (file);                InputStreamReader isr  = new inputstreamreader (out);                int ch = 0;                while  ((Ch = isr.read ())  != -1)  {                    system.out.print ((char)  CH);               }           } catch  (exception e)  {                // todo: handle exception            }       }  }  

Import Java.io.File;
Import Java.io.FileInputStream;
Import java.io.FileNotFoundException;
Import Java.io.FileOutputStream;
Import java.io.IOException;

Import Java.io.InputStreamReader; public class Testfile {/** * @param args */public static void main (string[] args) {//TODO Au to-generated method Stub//file (memory)----input stream----> "program"----output stream---->file (memory) file = new file ("D:/te
        MP "," Addfile.txt ");  try {file.createnewfile ();//Create File} catch (IOException e) {//TODO auto-generated catch
        Block E.printstacktrace (); //write content to file (output stream) String str = "Dear pumpkin."
        ";
        byte bt[] = new byte[1024];
        BT = Str.getbytes ();
            try {fileoutputstream in = new FileOutputStream (file);
                try {in.write (BT, 0, Bt.length);
                In.close ();
                Boolean success=true; System.out.println ("Write file successfully ");
            catch (IOException e) {//TODO auto-generated catch block E.printstacktrace (); The catch (FileNotFoundException e) {//TODO auto-generated catch block E.printstack
        Trace ();
            try {//Read the contents of the file (input stream) FileInputStream out = new FileInputStream (file);
            InputStreamReader ISR = new InputStreamReader (out);
            int ch = 0;
            while (ch = isr.read ())!=-1) {System.out.print ((char) ch); } catch (Exception e) {//Todo:handle Exception}}}


multiple ways to read files in Java


[Java] View Plain copy print? —————— reference ———————————   //  //1, read the contents of the file by byte   //2, read the file by character   //3, Read the contents of the file by line   //4, Random read the contents of the file       import java.io.bufferedreader;   Import  java.io.File;   import java.io.fileinputstream;   import java.io.filereader;    import java.io.ioexception;   import java.io.inputstream;   Import  java.io.InputStreamReader;   import java.io.randomaccessfile;   import  java.io.reader;      public class readfromfile {        /**       *  read files in bytes, often used to read binary files, such as pictures, sounds, images, and other files.        *        *  @param  filename        *             The name of the file &nbsP      */       public static void  Readfilebybytes (string filename)  {           file  file = new file (fileName);            inputstream in = null;           try {                system.out.println (" Reads the contents of the file in bytes and reads one byte at a time: ";               //   read one byte at a time                in =  new fileinputstream (file);                int tempbyte;                while  (tempbyte = in.read ())  != -1  {                    system.out.write (tempbyte);                }                in.close ();           }  catch  (ioexception e)  {                e.printstacktrace ();                return;           }            try {                SYSTEM.OUT.PRINTLN (Read the contents of the file in bytes, read multiple bytes at a time: ");                //  read multiple bytes at a time                 byte[] tempbytes = new byte[100];                int byteread = 0;                in = new fileinputstream (fileName);                readfromfile.showavailablebytes (in);                //  reads multiple bytes into a byte array, Number of bytes read in Byteread                while   ((Byteread = in.read (tempbytes))  != -1)  {                    system.out.write (Tempbytes, 0,  byteread);               }            } catch  (exception e1)  {                e1.printstacktrace ();            } finally {                if  (in != null)  {                    try {                        in.close ();                    }  catch  (ioexception e1)  {                    }               }            }       }           /**       *  read files in characters, often used to read text, numbers, and other types of files        *        *  @param  fileName       *             file name        */       public static void  Readfilebychars (string filename)  {           file  file = new file (fileName);            reader reader = null;           try {                SYSTEM.OUT.PRINTLN (Read the contents of the file in characters, one byte at a time: ");                //  read one character at a time                 reader = new  InputStreamReader (New fileinputstream (file));                int tempchar;                while  ((Tempchar = reader.read ())  != -1)  {                    //  for Windows, RN when the two characters are together, it represents a newline.                    //   But if these two characters are displayed separately, they will change the line two times.                    //  So, shield off R, or block N. Otherwise, there will be a lot more empty lines.                    if   (((char)  tempchar)  !=  ' R ')  {                        system.out.print ((char)   Tempchar);                    }               }               reader.close ();            } catch  (exception e)  {                e.printstacktrace ();            }           try {                SYSTEM.OUT.PRINTLN (Read the contents of the file in characters, read multiple bytes at a time: ");              

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.