需求:
将"E:/data/车站一次/阿坝藏族羌族自治州.csv"文件中的内容读取,写入到"E:/data//车站一次.csv"。
代码:
public class FileOpe { public static void main(String[] args) { sigle(); } public static void sigle(){ BufferedReader bufr = null; BufferedWriter bufw = null; try { FileReader fr = new FileReader( "E:/data/车站一次/阿坝藏族羌族自治州.csv"); bufr = new BufferedReader(fr); FileWriter fw = new FileWriter( "E:/data//车站一次.csv",true); bufw = new BufferedWriter(fw); String line = null; while((line=bufr.readLine())!=null){ bufw.write(line); bufw.newLine(); bufw.flush(); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally{ try { if(bufr!=null) bufr.close(); if(bufw!=null) bufw.close(); } catch (IOException e) { e.printStackTrace(); } } } }
但是,这样写程序会出现乱码问题,在用Java程序读写含中文的文件时,经常会出现乱码问题。
这是因为系统的编码和程序的编码采用了不同的编码格式。通常,windows自身擦采用的编码格式是gbk,
而IDE中Encode默认是utf-8的编码,这就是为什么会出现乱码的原因。为了避免可能得中文乱码问题,
最好在文件读取和写入的时候显式指定编码格式。
读文件:
public static String readFile(String fileName){ String fileContent = null; BufferedReader bufr = null; try{ File f = new File(fileName); InputStreamReader read = new InputStreamReader(new FileInputStream(f),"gbk"); bufr= new BufferedReader(read); String line = null; while ((line = bufr.readLine()) != null){ fileContent += line; } } catch (Exception e) { e.printStackTrace(); } finally{ read.close(); } return fileContent; }
写文件:
public static void writeFile(String fileName, String fileContent){ BufferedWriter bufw = null; try{ File f = new File(fileName); OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(f),"gbk"); bufw = new BufferedWriter(write); bufw.write(fileContent); } catch (Exception e) { e.printStackTrace(); } finally{ bufw.close(); } }
解决乱码问题后,代码如下:
public class FileDemo { public static void main(String[] args) { BufferedReader bufr = null; BufferedWriter bufw = null; try { FileInputStream in = new FileInputStream("E:/data/车站一次/阿坝藏族羌族自治州.csv"); InputStreamReader insr = new InputStreamReader(in, "gbk"); bufr = new BufferedReader(insr); FileWriter fw = new FileWriter("E:/data/a.csv", true); bufw = new BufferedWriter(fw); String line = null; while((line=bufr.readLine())!=null){ bufw.write(line); bufw.newLine(); bufw.flush(); } bufr.close(); bufw.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
这样就不会出现乱码问题。
Java底层代码实现单文件读取和写入(解决中文乱码问题)
时间: 2024-10-05 11:02:44