从指定文件(字节数组)获取内容以及获取长度

来源:互联网 发布:淘宝垃圾短信 编辑:程序博客网 时间:2024/05/29 03:27
package cn.felay.io;import java.io.ByteArrayInputStream;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;import java.io.InputStream;/** * @author <a mailto:felayman@163.com>felayman</a> * @timer 2014年6月10日 下午3:46:19 */public class InputStreamDemo {/** * 关闭输入流 *  * @param in */public void freeInputStream(InputStream in) {try {in.close();} catch (IOException e) {e.printStackTrace();}}/** * 获取输入流 *  * @param fileName * @return */public InputStream getInputStream(String fileName) {InputStream in = null;try {in = new FileInputStream(fileName);} catch (FileNotFoundException e) {e.printStackTrace();}return in;}/** * 从指定的文件中获取内容 *  * @param fileName * @return */public String getContentFromFile(String fileName) {InputStream in = this.getInputStream(fileName);byte[] b = new byte[1024];try {while (in.read(b) != -1) {}} catch (IOException e) {e.printStackTrace();} finally {this.freeInputStream(in);}String content = new String(b);content = content.trim();return content;}/** * 获取文件中字节长度 *  * @param fileName * @return */public int getLenFromFile(String fileName) {InputStream in = null;int len = 0;try {in = new FileInputStream(fileName);len = in.available();} catch (FileNotFoundException e) {System.out.println(e.getLocalizedMessage());} catch (IOException e) {e.printStackTrace();} finally {try {in.close();} catch (IOException e) {e.printStackTrace();}}return len;}/** * 从字节数组中获取字节长度 *  * @param b * @return */public int getLenFromByte(byte[] b) {InputStream in = null;in = new ByteArrayInputStream(b);int len = 0;try {len = in.available();} catch (IOException e) {e.printStackTrace();} finally {try {in.close();} catch (IOException e) {e.printStackTrace();}}return len;}public byte[] getContentFromString(String str) {byte[] b = str.getBytes();return b;}public static void main(String[] args) {// 获取文件中字节长度InputStreamDemo isd = new InputStreamDemo();String fileName = "src/res/test1.text";int fileLen = isd.getLenFromFile(fileName);System.out.println("文件长度为:" + fileLen);// 从指定文件获取内容String content = isd.getContentFromFile(fileName);System.out.println("获取的内容为:" + content);}}
0 0
原创粉丝点击