浅谈 java中 IO流 对文件的操作
案例分析
1. 向文件中写入字符串
public class FileTest {
public static void main(String[] args) {
File file = new File("C:\\Users\\Administrator\\Desktop\\hello.txt");
// 创建文件
try{
if (file.exists()){
file.delete();
file.createNewFile();
}else{
file.createNewFile();
}
/*
// 字符方式输出字符到文件
FileWriter writer = new FileWriter(file,true);
writer.write("您好");
writer.flush();
writer.close();
*/
// 字节流方式输出字符到文件
OutputStream out =new FileOutputStream(file);
String str="你好";
//将String 转化为 字节数组
byte[ ] b=str.getBytes();
out.write(b);
out.close();
}catch(IOException e){
e.printStackTrace();
}
}
2. 将指定目录下的文件复制到另一目录
public class BackUpDatas {
public static void main(String[] args) {
String srcPath ="D:\\d1";
String targetPath = "F:\\d1";
this.copyAllFile (srcPath,targetPath);
}
public void copyFile(String src, String target){
InputStream is = null;
OutputStream os = null;
try {
is = new FileInputStream(src);
os = new FileOutputStream(target);
byte[] buff = new byte[1024];
int len = 0;
// 以最多1024(buff.length)个字节的形式把文件读入缓存buff,以整数形式返回实际读取的字节数,如果因为已经到达流末尾而不再有数据可用,则返回 -1。
while((len = is.read(buff, 0, buff.length)) != -1) {
// 将存放在buff中的字节写入os输出流
os.write(buff, 0, len);
}
System.out.println("文件拷贝成功!");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(os!=null){
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(is!=null){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public void copyAllFile(String srcPath, String targetPath){
File f = new File(srcPath);
//数组形式接收指定路径下的所有文件
File[] fileList = f.listFiles();
//遍历数组
for(File f1 : fileList){
//判断是否为文件
if(f1.isFile()) {
copyFile(srcPath + "\\" + f1.getName(), targetPath + "\\" + f1.getName());
}
//判断是否是目录
else if(f1.isDirectory()) {
String childDirPath = targetPath + "\\" + f1.getName();
//创建新目录
File targetFile = new File(childDirPath);
if(!targetFile.exists()) {
targetFile.mkdirs();
}
copyAllFile(f1.getPath().toString(), childDirPath);
}
}
}
附 :字节流和字符流的区别(重点)
字节流和字符流的区别:(详细可以参见ttp://blog.****.NET/qq_25184739/article/details/51203733)
节流没有缓冲区,是直接输出的,而字符流是输出到缓冲区的。因此在输出时,字节流不调用colse()方法时,信息已经输出了,而字符流只有在调用close()方法关闭缓冲区时,信息才输出。要想字符流在未关闭时输出信息,则需要手动调用flush()方法。
· 读写单位不同:字节流以字节(8bit)为单位,字符流以字符为单位,根据码表映射字符,一次可能读多个字节。
· 处理对象不同:字节流能处理所有类型的数据(如图片、avi等),而字符流只能处理字符类型的数据。
结论:只要是处理纯文本数据,就优先考虑使用字符流。除此之外都使用字节流。