Home Java javaTutorial How to use Java to read and write files code explanation

How to use Java to read and write files code explanation

May 30, 2017 am 11:17 AM

Java的读写文件方法在工作中相信有很多的用处的,本人在之前包括现在都在使用Java的读写文件方法来处理数据方面的输入输出,确实很方便。奈何我的记性实在是叫人着急,很多时候既然都会想不起来怎么写了,不过我的Java代码量也实在是少的可怜,所以应该多多练习。这里做一个总结,集中在一起方面今后查看。

Java读文件

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 {
  
  /**
   * 采用的是操作系统底层默认的编码方式,GBK等,非UTF8
   * */
  
  /**
   * 以字节为单位读取文件内容,常用于读取二进制文件,比如图片、影像、声音等文件
   * */
  public static void readFileByBytes(String filename) {
    File file=new File(filename);
    FileInputStream in=null;
    try {
      System.out.println("以字节为单位读取文件,一次读一个字节: ");
      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("以字节为单位读取文件,一次读多个字节: ");
      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();
        } catch (IOException e1) {
          
        }
      }
    }
  }
  /**
   * 以字符为单位读取文件,常用于读文本,数字等类型的文件
   * */
  public static void readFileByChar(String filename) {
    File file=new File(filename);
    Reader reader=null;
    try {
      System.out.println("以字符为单位读取文件内容,一次一个字节:");
      //InputStreamReader类:是字节向字符转换的桥梁
      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("以字符为单位读取文件内容,一次读多个字节: ");
      char[] temp=new char[30];
      int charread=0;
      reader=new InputStreamReader(new FileInputStream(filename));
      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] == &#39;\r&#39;) {
              break;
            } else {
              System.out.println(temp[i]);
            }
          }
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      if (reader != null) {
        try {
          reader.close();
        } catch (IOException e) {
          
        }
      }
    }
  }
  /**
   * 以行为单位读取文件,常用于读面向行的格式化文件
   * */
  public static void readFileByLine(String filename) {
    File file=new File(filename);
    BufferedReader reader=null;
    try {
      System.out.println("以行为单位读取文件内容,一次读一整行: ");
      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();
        } catch (IOException e) {
          
        }
      }
    }
  }
  /**
   * 随机读取文件内容
   * */
  public static void readFileByRandomAccess(String filename) {
    RandomAccessFile randomfile=null;
    try {
      System.out.println("随机读取一段文件内容");
      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("当前字节输入流中的字节数为:" + 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);
  }
}
Copy after login

Java写文件

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:\\天才白痴梦\\JAVA";
    File file=new File("E:\\天才白痴梦\\JAVA","BaiYiShaoNian.txt");
    if (!file.exists()) {
      try {
        file.createNewFile();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    /**
     * Java写入文件的三种方法
     * */
    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(new File(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();
      }
    }
    
  }
}
Copy after login


The above is the detailed content of How to use Java to read and write files code explanation. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

See all articles