刚刚入门java,想把基础打好点。正好学到IO流,有错希望留言指出,不胜感激。
没有使用封装的工具类,框架。
使用的java自带的FileInputStream和FileOutputStream这是字节流类,任何文件都可以使用这两个类来进行传输。
大概的思路就是
第一步,创建所读文件和文件所写入的目录
第二步,选择某个流,进行操作
第三步,搬运文件
第四步,关闭流。流的关闭遵循 ‘ 先打开的后关闭 ’ 原则
注意点:
temp = is.read(bt,0,bt.length) 返回一个,读入 缓冲区的总字节数。从输入流读取数据,然后存储到bt字节数组中。
package ioBase;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class IOTest5 {
/*
* temp = is.read(bt,0,bt.length) 返回一个,读入 缓冲区的总字节数
* os.write(bt, 0, temp); temp不可以替换为bt.length(),因为bt数组的长度已经固定了
* 而temp可以实时反映出当前的数组里面有多少字节量
*/
public static void main(String[] args) {
FileInputStream is = null;
FileOutputStream os = null;
try {
is = new FileInputStream("陈粒 - 易燃易爆炸 [mqms2].flac");
//输出到src同级目录下,会自动创建。如果已经存在false会覆盖掉原先的内容,使用true会追加。默认是false
os = new FileOutputStream("result.flac");
//选择输入流
byte[] bt = new byte[1024*100];
int temp;//接收长度
while((temp = is.read(bt,0,bt.length))!= -1){
os.write(bt, 0, temp);
}
os.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
if(null != os){
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if((null != is){
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}