两种读取文件的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);
 
 
	}
 
}
如果你是一名技术人员可加我QQ 2651-0442-02,如果你是java技术人还可以加入QQ群 1784-9136-0
你将得到的不仅仅是技术的交流,还有职业机会,人生解惑.
首发地址:月小升博客http://java-er.com/blog/read-file-java/
无特殊说明,文章均为月小升原创,欢迎转载,转载请注明本文地址,谢谢
此条目发表在 JAVA 分类目录,贴了 , 标签。将固定链接加入收藏夹。
既然来了,就评论一下,不会怀孕的

发表评论

电子邮件地址不会被公开。 必填项已用 * 标注

*

您可以使用这些 HTML 标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">