Java reads file method summary

  • 2020-05-27 04:46:29
  • OfStack

The example in this paper shares the method of Java to read files for your reference. The details are as follows

1. Read file contents by byte
2. Read the contents of the file by characters
3. Read the contents of the file by line
4. Read file contents randomly


public class ReadFromFile {
  /**
   *  Reads a file in bytes, often used for reading 2 Base files, such as pictures, sounds, images, etc. 
   */
  public static void readFileByBytes(String fileName) {
    File file = new File(fileName);
    InputStream in = null;
    try {
      System.out.println(" Read the contents of the file in bytes, 1 Time to read 1 Bytes: ");
      // 1 Time to read 1 bytes 
      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, 1 Multiple bytes per read: ");
      // 1 Multiple bytes per read 
      byte[] tempbytes = new byte[100];
      int byteread = 0;
      in = new FileInputStream(fileName);
      ReadFromFile.showAvailableBytes(in);
      //  Reading multiple bytes into a byte array, byteread for 1 Number of bytes per read 
      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) {
        }
      }
    }
  }

  /**
   *  To read a file in character units, often used to read text, Numbers, and other types of files 
   */
  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, 1 Time to read 1 Bytes: ");
      // 1 Time to read 1 A character 
      reader = new InputStreamReader(new FileInputStream(file));
      int tempchar;
      while ((tempchar = reader.read()) != -1) {
        //  for windows Next, \r\n These two characters are in 1 When rising, represents 1 A line feed. 
        //  But if the two characters are displayed separately, the lines are changed twice. 
        //  So, shield it \r Or shielding \n . Otherwise, there will be many more blank 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, 1 Multiple bytes per read: ");
      // 1 Read more than one character at a time 
      char[] tempchars = new char[30];
      int charread = 0;
      reader = new InputStreamReader(new FileInputStream(fileName));
      //  Read multiple characters into a character array, charread for 1 Number of times read characters 
      while ((charread = reader.read(tempchars)) != -1) {
        //  Again shielding \r Don't show 
        if ((charread == tempchars.length)
            && (tempchars[tempchars.length - 1] != '\r')) {
          System.out.print(tempchars);
        } else {
          for (int i = 0; i < charread; i++) {
            if (tempchars[i] == '\r') {
              continue;
            } else {
              System.out.print(tempchars[i]);
            }
          }
        }
      }

    } catch (Exception e1) {
      e1.printStackTrace();
    } finally {
      if (reader != null) {
        try {
          reader.close();
        } catch (IOException e1) {
        }
      }
    }
  }

  /**
   *  Read a file as a behavior unit, often used to read a line-oriented formatted 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 as a behavior unit, 1 Time to read 1 The whole line: ");
      reader = new BufferedReader(new FileReader(file));
      String tempString = null;
      int line = 1;
      // 1 Time to read 1 Ok, until you read in null End for file 
      while ((tempString = reader.readLine()) != null) {
        //  According to the line Numbers 
        System.out.println("line " + line + ": " + tempString);
        line++;
      }
      reader.close();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      if (reader != null) {
        try {
          reader.close();
        } catch (IOException e1) {
        }
      }
    }
  }

  /**
   *  Read the contents of the file at random 
   */
  public static void readFileByRandomAccess(String fileName) {
    RandomAccessFile randomFile = null;
    try {
      System.out.println(" Random reads 1 Section file content: ");
      //  Open the 1 Three random access file streams, in a read-only mode 
      randomFile = new RandomAccessFile(fileName, "r");
      //  File length, number of bytes 
      long fileLength = randomFile.length();
      //  The start of the read file 
      int beginIndex = (fileLength > 4) ? 4 : 0;
      //  Moves the start of the read file to beginIndex Position. 
      randomFile.seek(beginIndex);
      byte[] bytes = new byte[10];
      int byteread = 0;
      // 1 Time to read 10 Bytes if the file is short of content 10 Bytes, read the remaining bytes. 
      //  will 1 The number of bytes assigned for each read byteread
      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 e1) {
        }
      }
    }
  }

  /**
   *  Displays the number of bytes left in the input stream 
   */
  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 = "C:/temp/newTemp.txt";
    ReadFromFile.readFileByBytes(fileName);
    ReadFromFile.readFileByChars(fileName);
    ReadFromFile.readFileByLines(fileName);
    ReadFromFile.readFileByRandomAccess(fileName);
  }
}

5. Append the content to the end of the file


public class AppendToFile {
  /**
   * A Method append file: use RandomAccessFile
   */
  public static void appendMethodA(String fileName, String content) {
    try {
      //  Open the 1 Random access to the file stream, by read and write 
      RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw");
      //  File length, number of bytes 
      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: use FileWriter
   */
  public static void appendMethodB(String fileName, String content) {
    try {
      // Open the 1 File writer, the first in the constructor 2 A parameter true Means to write a file as an append 
      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!";
    // According to the method A Additional documents 
    AppendToFile.appendMethodA(fileName, content);
    AppendToFile.appendMethodA(fileName, "append end. \n");
    // Display file contents 
    ReadFromFile.readFileByLines(fileName);
    // According to the method B Additional documents 
    AppendToFile.appendMethodB(fileName, content);
    AppendToFile.appendMethodB(fileName, "append end. \n");
    // Display file contents 
    ReadFromFile.readFileByLines(fileName);
  }
}

Related articles: