I/O流中的字节流的读取与输入
(用于读取写入二进制文件,如图片、声音、影响等类型文件)
1.对于文件的读取,输入流InputStream下的子类FileInputStream
有一个read()可以读取数据,read(byte[])这个方法需要传入一个参数
这个参数是一个byte型的数组,用于存储读取到的数据
2.把byte数组转化为string类型的数据方便使用
String str=new String(by)(by是byte型数组的名称)
读取完文件后需要关闭输入流,以免占用内存空间
3.完整的过程需要用try/catch来包住,以免程序发生错误而终止不了
读取文件代码示例:
public Static String getMsg(){
byte msg[]=new byte[100];
String str=null;
try{
InputStream is=new FileInputStream("src/a.txt");
is.read(msg);
str=new String(msg);
is.close();
}catch(FileNotFoundException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
return str;
}
方法写入数据到指定文件,write()方法需要传入一个byte[]数组,如果你想
传入String类型的数据,String类型数据有可以转化为byte[]的方法
写入文件代码示例:
public Static String putMsg(){
String msg=getMsg();
try{
OutputStream os=new FileOutputStream("src/b.txt",
true);
os.write(13);
os.wirte(10);
//在windows系统下,换行符用ASCII码表示是13 10,这里是
换行的意思
os.write(msg.getBytes());
//把String类型数据转化为byte[]数组
os.flush();
//刷新输出流
os.close();
}catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
5.上面是对于文本类型文件的读取与写入,但是图片、声音、影响文件不会把读取的数据转为String类型数据,而是直接用byte数组来存储数据,然后全写入另一个文件,相当于复制粘贴一个文件,这里需要注意的是读取与写入的文
件类型要一致,即文件的后缀名需要一致。
代码示例演示复制粘贴并打开声音文件:
public static void get(){
try{
InputStream is=new FileInputStream("E:\音乐\金娜英 -
说出心声.mp3");
OutputStream os=new FileInputStream("E:\Youku Files
\mymusic.mp3");
byte music[]=new byte[1024*10];
int len=0;
while((len=is.read(music))!=-1){
os.write(music);
}
is.close();
os.close();
}catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
String cmd="cmd /c\"文件路径.mp3\"";
Runtime run=Runtime.getRuntime();
try{
run.exec(cmd);
}catch (IOException e) {
e.printStackTrace();
}
//打开文件
}