Java—io学习笔记
package JFrameChat;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
public class StarmeChat {
public static void main(String[] args) {
// //输入流
// File f = new File("/Users/ZhengShaoru/Desktop/JframeTest.java"); // 文件的绝对路径
// try {
// InputStream in = new FileInputStream(f); // 字节流->文件字节流
// byte[] b = new byte[1024]; //定义一个字节型数组,每次读取1024个字节
// int len = 0;
// String str = "";
// while ((len = in.read(b)) != -1) { //定义每次读取文件存入数组的长度len,判定数组是否为空
// str += new String(b).trim(); //将每次读取的字符串去掉空格(trim)拼接
// b = new byte[1024];
// /*数组以覆盖形式存储,为避免下一次读取不足1024个字节,
// 数组后半部分仍旧存有上次读取数据,因此每次读取结束后应手动将数组指控*/
// }
// System.out.println(str);
// } catch (Exception e) {
// }
// //输出流
// File ff = new File("/Users/ZhengShaoru/Desktop/java/");
// ff.mkdirs();
// try {
// FileOutputStream out = new FileOutputStream(new File(ff,"kd.txt"));
// String str = "文件字节输出流";
// out.write(str.getBytes());
// out.flush(); //清空缓存
// out.close();
// }catch(Exception e) {
// }
//IO结合复制一个文件
File f = new File("/Users/ZhengShaoru/Desktop/JframeTest.java"); // 文件的绝对路径
File ff = new File("/Users/ZhengShaoru/Desktop/java1/");
ff.mkdirs();
InputStream in;
FileOutputStream out;
in = null;
out = null;
try {
in = new FileInputStream(f); // 字节流->文件字节流
out = new FileOutputStream(new File(ff,f.getName()));
byte[] b = new byte[1024]; //定义一个字节型数组,每次读取1024个字节
int len = 0;
while ((len = in.read(b)) != -1) { //定义每次读取文件存入数组的长度len,判定数组是否为空
out.write(b,0,len);
}
} catch (Exception e) {
}finally{
try{
if(out != null){
out.flush(); //清空缓存
out.close();
}
if(in != null){
in.close();
}
}catch(Exception e){
}
}
}
}