java多线程    Java入门    vsftp    ftp    linux配置    centos    FRP教程    HBase    Html5缓存    webp    zabbix    分布式    neo4j图数据库    

两种读取文件的java方法,java.io.file

两种读取文件的java方法
Two way for reading the files in java.

one,we don't need to know what is file's encoding
一个不用知道文件的编码
another,we must know the file's encoding before we read this file
另外一个,必须在读取之前知道文件编码

package com.javaer.examples.file;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;

public class ReadingFile {
	/**
	 * we don't need to know what is file's encoding
	 * @param path file path
	 * @return a string in the file
	 * @throws IOException
	 */
	public static String readFile(String path) throws IOException {
		BufferedReader input = new BufferedReader(new FileReader(path));
		String line = null;
		StringBuffer sb = new StringBuffer();
		while ((line = input.readLine()) != null) {
			sb.append(line);
			sb.append(System.getProperty("line.separator"));
		}
		input.close();
		return sb.toString();
	}
	/**
	 * we must know the file's encoding before we read this file
	 * @param path  file path
	 * @param encode the file's encode
	 * @return a string in the file
	 * @throws IOException
	 */
	public static String readFileEncoding(String path, String encode)
			throws IOException {
		InputStream r = new FileInputStream(path);
		ByteArrayOutputStream byteout = new ByteArrayOutputStream();
		byte tmp[] = new byte[256];
		byte context[];
		int i = 0;
		while ((i = r.read(tmp)) > 0) {
			byteout.write(tmp, 0, i);
		}
		context = byteout.toByteArray();
		String str = new String(context, encode);
		r.close();
		byteout.close();
		return str;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		String s = null;
		try {
			s = ReadingFile.readFile("E:/1.txt");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println(s);
		
		
		try {
			s = ReadingFile.readFileEncoding("E:/2.txt","UTF-8");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println(s);
		
		
	}

}


This entry was posted in JAVA and tagged , . Bookmark the permalink.
月小升QQ 2651044202, 技术交流QQ群 178491360
首发地址:月小升博客https://java-er.com/blog/read-file-java/
无特殊说明,文章均为月小升原创,欢迎转载,转载请注明本文地址,谢谢
您的评论是我写作的动力.

Leave a Reply