yangleilt 发表于 2013-2-7 03:39:20

java读取txt文件.以及解决其乱码问题..

java的io操作文件中数txt文件最简单了..
一般在读写时时候要注意乱码问题..这个问题数简单也不简单..
得从创建记事本开始说起.
   有两种创建方式:
      一、是程序创建:创建的时候回规定其编码方式
      二、是在桌面右键 新建 记事本。这时候一般我们都不会可以的去选择其编码方式
所以就会出现乱码的问题...

/*-------------------------------------------------------------------------*/
import java.io.*;
public class ReadWriteFile {

public static void main(String args[])
{
   try
   {
    File read=new File("E:\\test.txt");
    File write=new File("E:\\test1.txt");
    BufferedReader br=new BufferedReader(new FileReader(read));
    BufferedWriter bw=new BufferedWriter(new FileWriter(write));
    String temp=null;
    temp=br.readLine();
    while(temp!=null)
    {
   //System.out.println("写了一行");
   bw.write(temp+"\r\n");
   temp=br.readLine();
    }
    bw.close();
    br.close();
   }
   catch(FileNotFoundException e)
   {
    System.out.println("文件没有找到异常");
   }
   catch(IOException e)
   {
    System.out.println(e.getMessage());
   }
}
}

/*-------------------------------------------------------------------------*/
import java.io.*;
public class ReadWriteFile {

public static void main(String args[])
{
   try
   {
    File read=new File("E:\\test.txt");
    File write=new File("E:\\test1.txt");

    BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(read), "GBK"));
    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(write), "GBK"));
    String temp=null;
    temp=br.readLine();
    while(temp!=null)
    {
   //System.out.println("写了一行");
   bw.write(temp+"\r\n");
   temp=br.readLine();
    }
    bw.close();
    br.close();
   }
   catch(FileNotFoundException e)
   {
    System.out.println("文件没有找到异常");
   }
   catch(IOException e)
   {
    System.out.println(e.getMessage());
   }
}
}

/*----------------------------------------------------------------------------*/
这样改 大功告成.......................
页: [1]
查看完整版本: java读取txt文件.以及解决其乱码问题..