Java 文本指定和不指定编码读写 自动识别编码方式

不考虑编码直接读取

    public static String readText(String path){
        String text = "";
		try {
			FileInputStream fileInputStream = new FileInputStream(new File(path));
			InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
	        BufferedReader reader = new BufferedReader(inputStreamReader);
	        String line = null;
	        while ((line = reader.readLine()) != null) {
	            text += line + "\n";
	        }
	        reader.close();
		} catch (IOException e) {
			System.out.println("文本输出异常!");
		}
        return text.length()>0?text.substring(0, text.length()-1):"";
    }
    

不考虑编码直接写出

	public static void writeText(String path, String text){
		try {
			FileOutputStream fileOutputStream = new FileOutputStream(new File(path));
			OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream);
	        BufferedWriter writer = new BufferedWriter(outputStreamWriter);
	        writer.write(text);
	        writer.close();
		} catch (IOException e) {
			System.out.println("文本输出异常!");
		}
    }
 

按照指定编码读取

    public static String readText(String path, String encoding){
        String text = "";
		try {
			FileInputStream fileInputStream = new FileInputStream(new File(path));
			InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, encoding);
	        BufferedReader reader = new BufferedReader(inputStreamReader);
	        String line = null;
	        while ((line = reader.readLine()) != null) {
	            text += line + "\n";
	        }
	        reader.close();
		} catch (IOException e) {
			System.out.println("文本输出异常!");
		}
        return text.length()>0?text.substring(0, text.length()-1):"";
    }
    

按照指定编码写出

	public static void writeText(String path, String text, String encoding){
		try {
			FileOutputStream fileOutputStream = new FileOutputStream(new File(path));
			OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, encoding);
	        BufferedWriter writer = new BufferedWriter(outputStreamWriter);
	        writer.write(text);
	        writer.close();
		} catch (IOException e) {
			System.out.println("文本输出异常!");
		}
    }
 

自动识别文本编码

    public static String getEncoding(String path) throws Exception {  
        InputStream inputStream = new FileInputStream(path);    
        byte[] head = new byte[3];    
        inputStream.read(head);      
        String encodeing = "gb2312";
        if (head[0] == -1 && head[1] == -2 ) encodeing = "UTF-16";    
        else if (head[0] == -2 && head[1] == -1 ) encodeing = "Unicode";    
        else if(head[0]==-17 && head[1]==-69 && head[2] ==-65) encodeing = "UTF-8";    
        inputStream.close(); 
        return encodeing;  
    }  
    

注意,按照指定编码读取时,第一个字符可能为编码字符(指定编码类型),由此可导致第一个字符乱码,其余字符读取正常。此时将第一个字符丢弃即可!

发布了18 篇原创文章 · 获赞 0 · 访问量 687

猜你喜欢

转载自blog.csdn.net/weixin_45792450/article/details/103649879