import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class FileRead {
static Logger log=LoggerFactory.getLogger(FileRead.class);
public void readFile(String path){
File file=new File(path);
if(!file.exists()){
log.error("文件"+path+"不存在");
}
try {
InputStream in=new FileInputStream(file);
String content=getFullContent(in,"UTF-8");
System.out.println("content:sys:"+content);
log.debug("content:"+content);
//System.out.println("content:sys:"+getFullContent4(in,"UTF-8"));
} catch (FileNotFoundException e) {
log.error("文件"+path+"不存在");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static String getFullContent(InputStream in,String charset){
StringBuffer sb=new StringBuffer();
InputStreamReader inr = null;
try {
inr=new InputStreamReader(in,charset);
char[] ch=new char[1024];
int readCount=0;
while((readCount=inr.read(ch))!=-1){
sb.append(ch, 0, readCount);
}
} catch (UnsupportedEncodingException e) {
log.error("流数据编码失败");
} catch (IOException e) {
log.error("读取IO流失败",e);
}finally{
try {
inr.close();
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
public static byte[] readBytes(InputStream in){
BufferedInputStream bi=new BufferedInputStream(in);
ByteArrayOutputStream ba=new ByteArrayOutputStream(1024);
byte[] b=new byte[1024];
int size=0;
try {
while((size=bi.read(b))!=-1){
ba.write(b, 0, size);
}
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
bi.close();
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
byte[] content=ba.toByteArray();
try {
ba.flush();
ba.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return content;
}
public static String getFullContent4(InputStream in, String charset) throws UnsupportedEncodingException {
byte[]bytes=readBytes(in);
return new String(bytes,charset);
}
/**
* @param args
*/
public static void main(String[] args) {
FileRead fileRead=new FileRead();
fileRead.readFile("D://qnproc.sql");
}
}
java读取文件
猜你喜欢
转载自janzxx.iteye.com/blog/2024065
今日推荐
周排行