How Java reads files and writes to files (simple instance) _java

Source: Internet
Author: User

Java Code

public class ReadFromFile {/** * reads files in bytes and is often used to read binary files, such as pictures, sounds, images, and so on. 
    */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, 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, byteread the number of bytes read in while (Byteread = In.read (tempbytes))!=-1) {System.out.write (tempbyt 
      ES, 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 stat 
    IC void Readfilebychars (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: "); 
      Read one character at a time reader = new InputStreamReader (new FileInputStream (file)); 
      int Tempchar; 
        while ((Tempchar = Reader.read ())!=-1) {//for Windows, \ r \ n These two characters together indicate a newline. 
        However, if the two characters are displayed separately, the lines will be changed two times. So, block \ 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: "); 
      Read multiple characters at a time char[] Tempchars = new CHAR[30]; 
      int charread = 0; Reader =New InputStreamReader (FileName) (new FileInputStream); 
        Reads more than one character into an array of characters, charread as the number of read characters while (Charread = Reader.read (tempchars))!=-1) {//also shielded \ R does not display if ((Charread = = tempchars.length) && (tempchars[tempchars.length-1]!= ' \ R ')) {Syste 
        M.out.print (Tempchars); else {for (int i = 0; i < Charread i++) {if (tempchars[i] = ' \ r ') {Contin 
            Ue 
            else {System.out.print (tempchars[i]); 
    catch (Exception E1) {E1.printstacktrace ()}}}} 
        finally {if (reader!= null) {try {reader.close (); The catch (IOException E1) {}}}/** * Reads a file in a behavior unit and is often used to read a line-oriented format file/public static 
    void Readfilebylines (String fileName) {File File = new file (fileName); 
    BufferedReader reader = null; try {System.ouT.println ("read the contents of the file in a behavioral unit, read one whole line at a time:"); 
      reader = new BufferedReader (new FileReader (file)); 
      String tempstring = null; 
      int line = 1; Read one row at a time until you read null for file end while ((tempstring = Reader.readline ())!= null) {//Show line number System.out.pri 
        Ntln ("line" + Line + ":" + tempstring); 
      line++; 
    } reader.close (); 
    catch (IOException e) {e.printstacktrace (); 
        finally {if (reader!= null) {try {reader.close (); ' Catch (IOException E1) {}}}}/** * Random Read file content */public static void Readfileby 
    Randomaccess (String fileName) {randomaccessfile randomfile = null; 
      try {System.out.println ("read the contents of a file randomly:"); 
      Open a random Access file stream, read-only randomfile = new Randomaccessfile (FileName, "R"); 
      File length, byte number long filelength = Randomfile.length (); Read the starting position of the file int beginindex = (Filelength > 4)? 
      4:0; //move the start position of the read file to the Beginindex location. 
      Randomfile.seek (Beginindex); 
      byte[] bytes = new BYTE[10]; 
      int byteread = 0; 
      Read 10 bytes at a time and read the remaining bytes if the file content is less than 10 bytes. Assigns a read number of bytes to Byteread while ((byteread = randomfile.read (bytes))!=-1) {System.out.write (bytes, 0, byte 
      Read); 
    } catch (IOException e) {e.printstacktrace (); 
        finally {if (randomfile!= null) {try {randomfile.close (); The catch (IOException E1) {}}}/** * Displays the number of bytes left in the input stream * * private static void ShowA 
    Vailablebytes (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 = ' c:/temp/newtemp.txt '; 
    Readfromfile.readfilebybytes (FileName); 
    Readfromfile.readfilebychars (FileName); Readfromfile.readfilebylines (FileName);
    Readfromfile.readfilebyrandomaccess (FileName); } 
}

Java Code

public class Appendtofile {/** * A method Append file: Using randomaccessfile/public static void Appendmethoda (String fil ename, String content) {try {//Open a random Access file stream, read-write Randomaccessfile randomfile = new Randomaccessfile ( 
      FileName, "RW"); 
      File length, byte number long filelength = Randomfile.length (); 
      Moves the write file pointer to the end of the file. 
      Randomfile.seek (filelength); 
      Randomfile.writebytes (content); 
    Randomfile.close (); 
    catch (IOException e) {e.printstacktrace (); 
    /** * B method Append file: Using FileWriter */public static void Appendmethodb (string fileName, string content) { 
      try {//Open a write file, the second argument in the constructor is true to write the file in append form FileWriter writer = new FileWriter (FileName, true); 
      Writer.write (content); 
    Writer.close (); 
    catch (IOException e) {e.printstacktrace (); 
    } public static void Main (string[] args) {String fileName = ' c:/temp/newtemp.txt '; String content = "New append!"; 
    Append file Appendtofile.appendmethoda (filename, content) by method A; Appendtofile.appendmethoda (FileName, "append end.") 
    \ n "); 
    Displays the contents of the file Readfromfile.readfilebylines (fileName); 
    Append file Appendtofile.appendmethodb (filename, content) by method B; Appendtofile.appendmethodb (FileName, "append end.") 
    \ n "); 
  Displays the contents of the file Readfromfile.readfilebylines (fileName); } 
}

The above is a small series for everyone to read the Java file and write the file in the way (simple example) all content, I hope that we support 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.