Java language programming (15) read text file .txt through Java language

Java language to read text txt

  The general process of reading a text file is as follows:

(1) Construct a file object,

(2) Using file objects to construct Reader objects can be FileReader , InputStreamReader, etc. Use Reader objects to construct BufferedReader objects ( mainly use its readLine() method to read files by line )

(3) Read the file line by line, and process the string obtained in each line.

I usually use InputStreamReader . I set the class name as Doqu . First, I create a new text file test.txt in the E disk , that is, create a File class object, then create a FileInputStream class object to read File , create an InputStreamReader object to receive the file stream, and then create a reader buffer to load the file stream in Use the read.line() method to read the code line by line from the buffer, then output the file content line by line, and then close the data stream after the file is executed. The list of programs I wrote is as follows:

package doqu;

import java.io.BufferedReader;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.IOException;

import java.io.InputStreamReader;

/**

 *

 * @author john

 */

public class Duqu {

 

    /**

     * @param args the command line arguments

     */

    public static void main(String[] args) {

        // TODO code application logic here

       File file1 = new File("E:\\test.txt");

       FileInputStream fis = null;

       InputStreamReader isr = null;

       BufferedReader br = null;

       try {

           fis = new FileInputStream(file1);

           isr = new InputStreamReader(fis);

           br = new BufferedReader(isr);

                 String lineTxt = null;

           while ((lineTxt = br.readLine()) != null) {

               System.out.println(lineTxt);

           }

           

       }catch (FileNotFoundException e) {

           e.printStackTrace ();

       }catch (IOException e) {

           e.printStackTrace ();

       }

        finally {

           if (br != null) {

               try {

                   br.close();

               }catch (IOException e) {

                   e.printStackTrace ();

               }

           }

           if (isr != null) {

               try {

                   isr.close();

               }catch (IOException e) {

                   e.printStackTrace ();

               }

           }

           if (fis != null) {

               try {

                   fis.close();

               }catch (IOException e) {

                   e.printStackTrace();

           }

       }

    }

    }   

}

try语句出现异常时,会执行catch语句,我们将catch括号中的Exception e初始化,就是实例化Exception类型的对象,然后e引用调用再Excaption类中的方法,e.printStackTrace();这种方法的意思就是再命令行打印异常信息再程序中出错的位置及原因

OException e:代表捕捉的是输入输出异常。e是对象。即:如果发生输入输出的异常就会在这里捕捉IOException是Exception 的一种,也就是说如果换成了Exception的话除了能捕捉到IOException还能捕捉到其他的。如果同时用的话,必须是先用范围小的也就是IOException捕捉 然后再用范围大的Exception捕捉

 

图片

我在E盘的test.txt中输入数据,保存。

 

图片

程序可以正常运行,之后我将txt中的数字改为汉字

 

图片

图片

但是结果输出乱码,不能输出汉字。我在网上查找了原因及解决方法。

Java程序进行读写含中文的txt文件时,会出现读出或写入的内容会出现乱码。原因就是系统的编码和程序的编码采用了不同的编码格式。通常,我们不修改的话,windows自身采用的编码格式是gbk,而IDE中Encode不修改的话,默认是utf-8的编码。当在OS下手工创建并写入的txt文件(gbk),用程序直接去读(utf-8),就会乱码。为了避免可能的中文乱码问题,最好在文件写入和读出的时候显示指定编码格式

采用java.io.InputStreamReader和java.io.OutputStreamWriter来解决这个问题。在 InputStreamReader和OutputStreamWriter中,可以通过指定编码方式来完成gbk文件的读写。

我们在D盘中创建两个文本文件,一个为fileone.txt,另一个为filesecond.txt,类名为readandwrite程序清单如下:

package readandwrite;

import java.io.BufferedReader;

import java.io.BufferedWriter;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.OutputStreamWriter;

 *

 * @author john

 */

public class ReadandWrite {

 

    /**

     * @param args the command line arguments

     */

    public static void main(String[] args) {

 

        File firstFile = new File("D://fileone.txt");  

        File secondFile=new File("D://filesecond.txt");  

        BufferedReader in = null;  

        BufferedWriter out = null;        

        try { in = new BufferedReader(new InputStreamReader(new FileInputStream(firstFile), "gbk"));  

            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(secondFile), "gbk"));  

            String line = "";  

            while((line = in.readLine())!=null){  

                System.out.println(line);  

                out.write(line+"\r\n");  

            }  

        } catch (FileNotFoundException e) {  

            System.out.println("file is not fond");  

        } catch (IOException e) {  

            System.out.println("Read or write Exceptioned");  

        }finally{             

            if(null!=in){   

                try {  

                    in.close();  

                } catch (IOException e) {  

                    e.printStackTrace();  

                }}  

            if(null!=out){  

                try {  

                    out.close();  

                } catch (IOException e) {  

                    e.printStackTrace();  

                }}}}

}

 我用in = new BufferedReader(new InputStreamReader(new FileInputStream(firstFile), "gbk"));out =new BufferedWriter(new OutputStreamWriter(new FileOutputStream(secondFile), "gbk"));来指定编码方式,一定要写BufferedWriter out的close不然什么都不会被写入文件的,写入换行时,一定要\r\n,否则无效

 

图片

我们在fileone中输入汉字和字符,之后运行程序。

 

图片

    结果可以输出汉字和字符,方法正确,成功运行,同时,fileone中的输入也会复制到filesecond中。


Guess you like

Origin blog.51cto.com/15064656/2602765