您的位置:首页 > 其它

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

2016-12-07 11:20 316 查看
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);
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐