Simple Java read file sample sharing

  • 2020-04-01 02:52:18
  • OfStack

It can be understood as follows:

You first get a file handle. File = new File(); File is the file handle. The two connected to the telephone network. Now you can start making phone calls

This line reads the information of party a: new FileInputStream(file) this information has been read into memory. The following shall be interpreted as something that can be understood by party b

Now that you're using a FileInputStream(). So you need to use the InputStreamReader() method to interpret the data that was just loaded into memory

When the reading is done, output it. That, of course, translates to data that IO can recognize. Then you need to call the bytecode reading method BufferedReader(). Use the readline() method of bufferedReader() to read each line in the TXT file.


package com.campu;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.Reader;

public class H20121012 {
    
    public static void readTxtFile(String filePath){
        try {
                String encoding="GBK";
                File file=new File(filePath);
                if(file.isFile() && file.exists()){ //Determine if the file exists
                    InputStreamReader read = new InputStreamReader(
                    new FileInputStream(file),encoding);//Consider the encoding format
                    BufferedReader bufferedReader = new BufferedReader(read);
                    String lineTxt = null;
                    while((lineTxt = bufferedReader.readLine()) != null){
                        System.out.println(lineTxt);
                    }
                    read.close();
        }else{
            System.out.println(" The specified file could not be found ");
        }
        } catch (Exception e) {
            System.out.println(" Error reading file contents ");
            e.printStackTrace();
        }

    }

    public static void main(String argv[]){
        String filePath = "L:\Apache\htdocs\res\20121012.txt";
//      "res/";
        readTxtFile(filePath);
    }

     

}


Related articles: