Java I/O流-总结(InputStream,OutputStream,Reader,Writer) (二)

2014-11-24 08:16:56 · 作者: · 浏览: 3
logger.debug(tempchars[i]);

}

}

}

}

}

} catch (Exception e1) {

logger.error("读取文本文件异常",e1);

} finally {

if (reader !=null) {

try {

reader.close();

} catch (IOException e1) {

logger.error("读取文本文件异常",e1);

}

}

}

}



/**

*以行为单位读取文件,常用于读面向行的格式化文件

*@paramfileName:文件名

*/

publicstatic List readFileByLines(StringfileName) {

List list = new ArrayList();

if(fileName!=null&&!"".equals(fileName)){

File file = new File(fileName);

BufferedReader reader = null;

try {

logger.debug("以行为单位读取文件内容,一次读一整行:");

reader = new BufferedReader(new FileReader(file));

String tempString = null;

/*一次读入一行,直到读入null为文件结束*/

while ((tempString = reader.readLine()) !=null) {

logger.debug(tempString);

list.add(tempString);

}

} catch (IOException e) {

logger.error("读取文本文件异常",e);

} finally {

if (reader !=null) {

try {

reader.close();

} catch (IOException e1) {

logger.error("读取文本文件异常",e1);

}

}

}

}

return list;

}





















5.2、常用写文件:

/**

*把内容写到文件

*@paramfilePathName文件名

*@paramList文件内容

*/

publicstaticboolean writerFile(String filePathName,String content){

boolean flag=false;

OutputStreamWriter osw=null;

try {

if(filePathName!=null&&!"".equals(filePathName)){

osw = new OutputStreamWriter(new FileOutputStream(filePathName));

}

} catch (FileNotFoundException e1) {

flag=false;

e1.printStackTrace();

}

if(osw!=null){

BufferedWriter bw=new BufferedWriter(osw);

try {

if(content!=null&&!"".equals(content)){

bw.write(content);

flag= true;

}

} catch (IOException e) {

flag=false;

e.printStackTrace();

}finally{

try {

bw.close();

osw.close();

} catch (IOException e) {

flag=false;

e.printStackTrace();

}

}

}

return flag;

}





/**

*把内容写到文件或追加到文件中

*@paramfilePathName文件名

*@paramList文件内容

*/

publicstaticboolean writerFileIsAppend(String filePathName,String content){

boolean flag=false;

OutputStreamWriter osw=null;

try {

if (filePathName!=null&&!"".equals(filePathName)) {

osw = new OutputStreamWriter(new FileOutputStream(filePathName,true));

}

} catch (Exception e1) {

flag=false;

e1.printStackTrace();