java的文件操作注意事项

在java中文件操作,创建文件的时候注意:举个例子说明问题

将c:/temp.txt文件 copy 到D:/test/java/file/这个目录下创建一个文件:temp.txt。

这样容易遗漏掉一个问题:

如果不存在路径d:/text/java/file。也就是说d盘肯可能根本就没有text这个文件夹,或者d:/text文件夹内没有java文件夹,或者d:/text/java文件夹没有file文件夹。会出现什么情况?

起初我认为系统会帮助我们创建,其实,不是的。

如果在目的地没有这个路径,会出现FileNotFound异常。

所有在进行文件创建操作一定要分为两步:

1.判断是否路径存在 2.创建文件

String filePath = "d://text/java/file//temp.txt";
String dirPath = filePath.substring(filePath,0,filePath.lastIndexOf("//"));
File dir = new File(dirPath);//1.创建文件所在的目录
if(!dir.exists()){
    dir.mkdirs();//注意mkdir()方法的区别
}
File file = new File(filePath);
if(!file.exists()){
   file.createNewFile();
}
FileInputStream in = new FileInputStream(new File("c://temp.txt"));
FileOutputStream out  = new FileOutputStream(file);
int len = 0;
byte[] buffer = new byte[128];
while((len=in.read(buffer))>0){
    out.write(buffer,0,len);
}
package com.hexiang.utils; import java.io.*; /** * FileUtil. Simple file operation class. * * @author BeanSoft * */ public class FileUtil { /** * The buffer. */ protected static byte buf[] = new byte[1024]; /** * Read content from local file. FIXME How to judge UTF-8 and GBK, the * correct code should be: FileReader fr = new FileReader(new * InputStreamReader(fileName, "ENCODING")); Might let the user select the * encoding would be a better idea. While reading UTF-8 files, the content * is bad when saved out. * * @param fileName - * local file name to read * @return * @throws Exception */ public static String readFileAsString(String fileName) throws Exception { String content = new String(readFileBinary(fileName)); return content; } /** * 读取文件并返回为给定字符集的字符串. * @param fileName * @param encoding * @return * @throws Exception */ public static String readFileAsString(String fileName, String encoding) throws Exception { String content = new String(readFileBinary(fileName), encoding); return content; } /** * 读取文件并返回为给定字符集的字符串. * @param fileName * @param encoding * @return * @throws Exception */ public static String readFileAsString(InputStream in) throws Exception { String content = new String(readFileBinary(in)); return content; } /** * Read content from local file to binary byte array. * * @param fileName - * local file name to read * @return * @throws Exception */ public static byte[] readFileBinary(String fileName) throws Exception { FileInputStream fin = new FileInputStream(fileName); return readFileBinary(fin); } /** * 从输入流读取数据为二进制字节数组. * @param streamIn * @return * @throws IOException */ public static byte[] readFileBinary(InputStream streamIn) throws IOException { BufferedInputStream in = new BufferedInputStream(streamIn); ByteArrayOutputStream out = new ByteArrayOutputStream(10240); int len; while ((len
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值