您的位置:首页 > 编程语言 > Java开发

Java 文件读取

2016-01-12 19:23 375 查看
public class FileUtil {

private static Logger logger = Logger.getLogger(FileUtil.class);

public static void fileWrite(String filePath ,String str)
{
try
{
createFile(filePath);
File file=new File(filePath);
FileOutputStream out=new FileOutputStream(file,false); //如果追加方式用true ,即文件的内容不会清空,在文件后面添加。
StringBuffer sb=new StringBuffer();
sb.append(str);
out.write(sb.toString().getBytes());//注意需要转换对应的字符集
out.close();
}
catch(Exception ex)
{
ex.printStackTrace();
logger.warn(ex);
}
}

public static String fileRead(String filePath)
{
String tempstr="-";
try
{
createFile(filePath);
File file=new File(filePath);

//	            BufferedReader br=new BufferedReader(new FileReader(file));
//	            while((tempstr=br.readLine())!=null)
//	                sb.append(tempstr);
//另一种读取方式
FileInputStream fis=new FileInputStream(file);
BufferedReader br=new BufferedReader(new InputStreamReader(fis));
tempstr = br.readLine();
if(tempstr == null)
tempstr = "-";
br.close();
}
catch(Exception ex)
{
ex.printStackTrace();
logger.warn(ex);
}
return tempstr;
}

public static void createFile(String path) throws Exception {

if (path.length() <=0) {
return;
}
try {
// 获得文件对象
File f = new File(path);
if (f.exists()) {
return;
}
// 如果路径不存在,则创建
if (!f.getParentFile().exists()) {
f.getParentFile().mkdirs();
}
f.createNewFile();
} catch (Exception ex) {
ex.printStackTrace();
logger.warn(ex);
}
}
}


read:如果文件不存在,报文件不存在错误

writer: 如果文件不存在,则创建文件,进行写。如果目录也不存在,会报错。

参考:
http://blog.csdn.net/jiangxinyu/article/details/7885518/ http://www.cnblogs.com/zhuocheng/archive/2011/12/12/2285290.html
Java读取文件内容的几种方式
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: