文件拷贝
快捷键:ctrl alt T 捕获异常代码块
public void fileCopy(){
FileInputStream is =null; //只能定义在try外,不然finally不能用了
FileOutputStream os =null;
try {
//★文件必须是先存在的才能移动,若不存在文件名则出错!
★ is = new FileInputStream("E://aa.txt");
★ os = new FileOutputStream("F://aa.txt");
★ byte[] buffer =new byte[1024];
int len;
//这里要加IOException e的检查时异常捕获
★ while((len=is.read(buffer))!=-1){ //!忘了传参,流要读到buffer!!!
★ os.write(buffer,0,len);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(is!=null){ //忘了怎么写这个判断
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(os!=null){
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
io流读文件内容
问题:无法将类 com.sun.org.apache.xpath.internal.operations.String中的构造器 String应用到给定类型 ,不import 此包即可
字节流读:
@Test
public void fileRead() throws Exception {
FileInputStream is = new FileInputStream("F://aa.txt");
byte[] buffer =new byte[16];
int len;
while((len=is.read(buffer))!=-1){
String s = new String(buffer, 0, len);
System.out.println(s);
}
is.close();
}
注意:标准写法得用try catch,这里只是为了好看
字符流读:
public void fileReadChar() throws Exception {
FileReader fileReader = new FileReader("F://aa.txt");
char[] buffer=new char[1024];
★ int len; //不是int你循环的-1怎么来比较???
while((len=fileReader.read(buffer))!=-1){
String str = new String(buffer, 0, len);
System.out.println(str);
}
fileReader.close();
}
处理流读:
public void bufferReader() throws Exception {
FileReader fr = new FileReader("F://aa.txt");
★ BufferedReader bf = new BufferedReader(fr);
String str;
//方便,直接可以按行读
while ((str=bf.readLine())!=null){
System.out.println(str);
}
fr.close();
bf.close();
}
io流写内容至文件
public void fileWrite() throws Exception {
FileWriter fw = new FileWriter("F://aa.txt");
fw.write("hhhkhkl哈哈");
fw.flush(); //★清空缓冲区,相当把管道里的水清空
fw.close();
}
向文件中追加内容而非覆盖:FileWriter()加一个参数:true,开启追加功能
FileWriter fw = new FileWriter(“F://aa.txt”,true);
对象序列化:实体类要实现Serializable接口
序列化:把内存中的内容转换成01机器码放到磁盘,反序列化相反。
public void testObjectOut() throws Exception{
//怼了一个string
InputStream is = new FileInputStream("E:\\test\\a\\user.txt");
★ObjectInputStream oi = new ObjectInputStream(is);
User user = (User)(oi.readObject());
System.out.println(user.getName());
is.close();
oi.close();
}