package toolClass;import java.io.BufferedReader;import java.io.File;import java.io.FileInputStream;import java.io.FileReader;import java.io.IOException;import java.io.InputStream;import java.io.Reader;/*** 多种方式读文件内容。**/public class ReadFromFile {/*** 以字节为单位读取文件,常用于读二进制文件,如图片、声音、影像等文件。* @param fileName :文件路径* @return 从文件中读取的字节数组*/public byte[] readFileByBytes(String fileName){// 通过路径创建文件对象File file = new File(fileName);InputStream in = null;byte[] tempbytes = null ;try {// 通过文件对象实例化FileInputStream对象,再同通过向上转型,实例化接口InputStreamin = new FileInputStream(file);// 返回输入流中的字节长度int length=in.available();// 实例化接收的字节数组tempbytes = new byte[length];// 把字节流中的数据读入字节数组中in.read(tempbytes);} catch (IOException e) {e.printStackTrace();} finally {if (in != null){try {in.close();} catch (IOException e) {e.printStackTrace();}}}return tempbytes;}/*** 以字符为单位读取文件,常用于读文本,数字等类型的文件* @param fileName:文件的路径* @return 返回一个字符串*/public String readFileByChars(String fileName){File file = null;Reader reader = null;BufferedReader bf =null;String result="";try {// 通过文件路径创建文件对象file=new File(fileName);//一次读多个字符reader = new FileReader(file);bf = new BufferedReader(reader);//读取一行数据;String temp;while ((temp=bf.readLine())!=null) {result+=temp+"\n";}} catch (Exception e1) {e1.printStackTrace();}finally {if (reader != null){try {bf.close();reader.close();} catch (IOException e1) {e1.printStackTrace();}}}return result;}}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。