zoukankan      html  css  js  c++  java
  • java 读写UTF-8文件的方法

    需导入的包:

    import java.io.BufferedReader;
    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;
    import java.io.UnsupportedEncodingException;
    import java.util.List;
    

        

    java 读写UTF-8文件的方法: 

    	private static void readUtf8File(String fileName) {
    		// 以UTF-8编码读取文件:
    		FileInputStream fis = null;
    		InputStreamReader isr = null;
    		String fileContent = "";
    
    		try {
    			fis = new FileInputStream(fileName);
    			isr = new InputStreamReader(fis, "UTF-8");
    			BufferedReader br = new BufferedReader(isr);
    			String line = null;
    			while ((line = br.readLine()) != null) {
    				fileContent += line;
    				fileContent += "
    "; // 补上换行符
    			}
    			System.out.println(fileContent);
    
    		} catch (FileNotFoundException e) {
    			e.printStackTrace();
    		} catch (UnsupportedEncodingException e) {
    			e.printStackTrace();
    		} catch (IOException e) {
    			e.printStackTrace();
    		} finally {
    			try {
    				isr.close();
    			} catch (IOException e) {
    				e.printStackTrace();
    			}
    		}
    	}
    

      

    调用例子: 

    	public static void main(String[] args) throws Exception {
    		// 读取UTF-8文件
    		readUtf8File("d:\test.txt");
    		// 写入UTF-8文件
    		writeUtf8File("d:\test1.txt","要写入文件的内容");
    	}
    

      

  • 相关阅读:
    C语言寒假大作战02
    C语言寒假大作战01
    C语言I作业12
    C语言I博客作业11
    C语言I博客作业10
    C语言I博客作业09
    C语言I作业08
    C语言ㅍ作业01 结构:通讯录
    C语言寒假大作战04
    C语言寒假大作战03
  • 原文地址:https://www.cnblogs.com/wzihan/p/15312048.html
Copyright © 2011-2022 走看看