Java Read and Write file Method summary (recommended) _java

Source: Internet
Author: User

Java read and write file methods in the work believe that there are many uses, I have included now in the use of Java read and write file methods to deal with data input and output, it is really convenient. But my memory is really called people worried, many times since will not think how to write, but my Java code is really little poor, so should be a lot of practice. Here is a summary, focus on the future view.

Java Read files

Package Genius idiot Dream;
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 Javaio {/** * uses the operating system's underlying default encoding, GBK, etc., non-UTF8 *//** * Reads the contents of the file in bytes and is often used to read binary files, such as pictures, images, sounds, etc.
    FILE * */public static void Readfilebybytes (String filename) {file file=new file (filename);
    FileInputStream In=null;
      try {System.out.println (reads a file in bytes, one byte at a time: ");
      In=new fileinputstream (file);
      int temp=0;
      while ((Temp=in.read ())!=-1) {System.out.println (temp);
    } in.close ();
      catch (IOException e) {e.printstacktrace ();
    return;
      try {System.out.println (read a file in bytes, read multiple bytes at a time: ");
      Byte[] Temp=new byte[100];
      int byteread=0;
      In=new fileinputstream (file); Javaio.showavailablebytes(in);
      while ((Byteread=in.read (temp))!=-1) {System.out.write (temp,0,byteread);
    } catch (Exception E1) {e1.printstacktrace ();
        Finally {if (in!= null) {try {in.close (); The catch (IOException E1) {}}}/** * reads files in characters, often used for reading text, numbers, and other types of files * */public s
    tatic void Readfilebychar (String filename) {file file=new file (filename);
    Reader Reader=null;
      try {System.out.println (reads the contents of the file in characters, one byte at a time: ");
      InputStreamReader class: Is a byte to character conversion of the bridge Reader=new InputStreamReader (new FileInputStream (file));
      int temp;
        while ((Temp=reader.read ())!=-1) {if ((char) temp)!= ' \ R ') {System.out.println ((char) temp);
    } 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: ");
      Char[] Temp=new char[30];
      int charread=0; Reader=New InputStreamReader (filename) (new FileInputStream);  while ((Charread=reader.read (temp))!=-1) {if (Charread = = temp.length) && (temp[temp.length-1]!= ' \ R '))
        {System.out.println (temp);
            else {for (int i=0; i<charread; i++) {if (temp[i] = = ' \ r ') {break;
            else {System.out.println (temp[i]);
    catch (Exception e) {e.printstacktrace ()}}}}
        finally {if (reader!= null) {try {reader.close (); The catch (IOException e) {}}}}/** * Reads a file in a behavior unit and is often used to read a line-oriented format file */public Stati
    c void Readfilebyline (String filename) {file file=new file (filename);
    BufferedReader Reader=null;
      try {System.out.println ("reads the contents of the file in a unit of behavior, reads one whole line at a time:");
      Reader=new BufferedReader (new FileReader (file));
      String Temp=null;
      int line=1; while (temp=Reader.readline ())!= null) {System.out.println ("line" + Line + ":" + temp);
      line++;
    } reader.close ();
    catch (IOException e) {e.printstacktrace ();
        finally {if (reader!= null) {try {reader.close (); The catch (IOException e) {}}}}/** * Random Read file content */public static void ReadFile
    Byrandomaccess (String filename) {randomaccessfile randomfile=null;
      try {System.out.println ("read the contents of a file randomly");
      Randomfile=new randomaccessfile (filename, "R");
      Long Filelength=randomfile.length ();
      int beginindex= (Filelength > 4? 4:0);
      Randomfile.seek (Beginindex);
      Byte[] Bytes=new byte[10];
      int byteread=0;
      while ((Byteread=randomfile.read (bytes))!=-1) {System.out.write (bytes,0,byteread);
    } catch (IOException e) {e.printstacktrace ();
          finally {if (randomfile!= null) {try {Randomfile.close (); catch (IOException e) {}}} private static void Showavailablebytes (InputStream in)
    {try {System.out.println (the number of bytes in the current byte input stream is: + in.available ());
    catch (IOException e) {e.printstacktrace ();
    } public static void Main (string[] args) {String filename= "e:\\baiyishaonian.txt";
    Javaio.readfilebybytes (filename);
    Javaio.readfilebychar (filename);
    Javaio.readfilebyline (filename);
  javaio.readfilebyrandomaccess (filename); }
}

Java Write files

Package Genius idiot Dream;
Import Java.io.BufferedWriter;
Import Java.io.File;
Import java.io.FileNotFoundException;
Import Java.io.FileOutputStream;
Import Java.io.FileWriter;
Import java.io.IOException;

Import Java.io.OutputStreamWriter;
    public class JavaIO2 {public static void main (string[] args) throws IOException {String path= "e:\\ genius idiot Dream \\JAVA";
    File File=new file ("e:\\ Genius idiot Dream \\JAVA", "BaiYiShaoNian.txt");
      if (!file.exists ()) {try {file.createnewfile ();
      catch (IOException e) {e.printstacktrace ();
    }/** * Java write file three methods * * */FileOutputStream fos=null;
    BufferedWriter Bw=null;
    FileWriter Fw=null;
    
    int value=1000;
      try {fos=new FileOutputStream (new File (path+ "Fos.txt"));
      Long Begin=system.currenttimemillis ();
      for (int i=1; i<=value; i++) {fos.write (5);
      Long End=system.currenttimemillis (); System.out.println ("Thecosttime of FileOutputStream is:" + (ENd-begin));
      
      Fos.close ();
      Bw=new BufferedWriter (New OutputStreamWriter (New FileOutputStream (path+ "Br.txt")), "UTF8");
      Begin=system.currenttimemillis ();
        for (int i=1; i<=value; i++) {bw.write (5);
      Bw.newline ();
      } bw.close ();
      End=system.currenttimemillis ();
      
      System.out.println ("Thecosttime of BufferedWriter is:" + (End-begin));
      Fw=new FileWriter (path+ "Fw.txt");
      Begin=system.currenttimemillis ();        
      for (int i=1; i<=value; i++) {fw.write (5);
      } fw.close ();
      End=system.currenttimemillis ();
      
      
    System.out.println ("Thecosttime of FileWriter is:" + (End-begin));
    catch (Exception e) {//TODO auto-generated catch block E.printstacktrace (); Finally {try {fos.close ();//fileoutputstream bw.close ();//bufferedwriter fw.close (); /filewriter} catch (Exception e) {e.printsTacktrace (); }
    }
    
  }
}

The above Java read and write file Method summary (recommended) is a small series to share all the content, hope to give you a reference, but also hope that we support the cloud habitat community.

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.