本人的GitHub:戳我一下
示例(一)——File类的基本用法
/**
* File类的基本用法
*/
package com.yifanjia.one;
import java.io.*;
public class IO1 {
public static void main(String[] args) {
// //得到文件对象
// File f =new File("I:\\11.txt");
// //得到文件的路径
// System.out.println("文件路径"+f.getAbsolutePath());
// //得到文件的大小
// System.out.println("文件大小"+f.length()+"个字节");
//创建文件
// File f = new File("I:\\12.txt");
// if(!f.exists()) {
// //可以创建
// try {
// f.createNewFile();
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// }
// else {
// System.out.println("有文件,不能创建");
//创建文件夹
// File f =new File("d:\\ff");
// if(f.isDirectory()) {
// System.out.println("文件夹存在");
// }
// else {
// f.mkdirs();
// }
//列出一个文件夹下面的所有文件
File f = new File("I:\\项目");
if(f.isDirectory()) {
File[] lists = f.listFiles();
for(File t : lists) {
System.out.println("文件名 "+t.getName());
}
}
}
}
示例(二)——图片拷贝
/**
* 图片拷贝
*/
package com.yifanjia.one;
import java.io.*;
public class IO5 {
public static void main(String[] args) {
//思路:先把图片读入到内存,再把图片写入到文件
//因为是二进制未见,只能用字节流完成
File f1 = new File("I:\\java\\TankGame\\src\\bomb_1.gif");
//if(!f1.exists()) System.out.println("dsasdas");
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream(f1);
fos = new FileOutputStream("D:\\11.gif");
byte[] buf = new byte[1024];
int n = 0;
while((n = fis.read(buf)) != -1) {
//输出到指定文件
fos.write(buf);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
fis.close();
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
示例(三)——缓冲字符流案例
/**
* 演示缓冲字符流案例
*/
package com.yifanjia.one;
import java.io.*;
public class IO4 {
public static void main(String[] args) {
BufferedReader br = null;
BufferedWriter bw = null;
FileReader fr = null;
FileWriter fw = null;
// TODO Auto-generated method stub
try {
//先构建一个FileReader
fr = new FileReader(new File("I:\\11.txt"));
fw = new FileWriter(new File("I:\\21.txt"));
br = new BufferedReader(fr);
bw = new BufferedWriter(fw);
String s = "";
while((s = br.readLine()) != null) {
//输出到文件
bw.write(s+"\r\n");
}
} catch (Exception e) {
e.printStackTrace();
// TODO: handle exception
} finally {
try {
br.close();
bw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}