package org.westos.IO流博客练习;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* IO:在设备和设备之间的一种数据传输!
* IO流的分类:
* 按流的方向分:
* 输入流: 读取文件 (e:\\a.txt):从硬盘上文件读取出来后输出这个文件的内容
* 输出流: 写文件:将e:\\a.txt 内容读出来--->写到f盘下
* 按数据的类型划分:
* 字节流
* 字节输入流:InputStream :读取字节
* 字节输出流:OutputStream :写字节
* 字符流
* 字符输入流:Reader :读字符
* 字符输出流:Writer :写字符
* 需求:在当项目下输出一个文件,fos.txt文件(文本文件)
* 只要文本文件,优先采用字符流,字符流在字节流之后出现的
* 使用字节流进行操作
* 无法创建字节输出流对象:OutputSteam :抽象类,不能实例化
* 又学习过File类,并且当前是对文件进行操作,子类:FileOutputSteam进行实例化
*
* File+InputStream
* File+OutputStream
* FileXXX (FileReader)
* FileXXX (FileWriter)
*
* 开发步骤:
* 1)创建字节输出流对象
* 2)写数据
* 3)关闭资源
* 关于字节输出流写数据的方法
* public void write(int b):一次写一个字节
* public void write(byte[] b) :一次写一个字节数组
* public void write(byte[] b, int off,int len):一次写一部分字节数组
* */
public class Text1 {
public static void main(String[] args) throws IOException {
FileOutputStream f = new FileOutputStream("E:\\demo\\apple\\apple.txt");
//若是找不到指定的路径,则java.io.FileNotFoundException
//若是找不到文件,则会创建一个文件
f.write("hello world!".getBytes());//需要将String转化为byte类型
byte[] by = {45,56,57,58,59};
//写入一个字节数组
f.write(by);
//关闭资源
f.close();
//在文本中的内容为hello world!-89:;
}
}
package org.westos.IO流博客练习;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* 换行符:
* windows: \r\n
* Linx:\n
* mac:\r
* public FileOutputStream(File file, boolean append):指定为true,末尾追加数据
* */
public class Text2 {
public static void main(String[] args) throws IOException {
FileOutputStream f = new FileOutputStream("E:\\demo\\apple\\apple.txt",true);
f.write("\r\n".getBytes());
f.write("ABCD".getBytes());
f.close();
}
}
package org.westos.IO流博客练习;
import java.io.FileInputStream;
import java.io.IOException;
/**
* 读取数据:
* InputStream抽象类:字节输入流
* FileInputStream
* 构造方法:
* public FileInputStream(String name)
* 开发步骤:
* 1)创建字节文件输入流对象
* 2)读数据
* 3)释放资源
*
* 读数据方式:
* public abstract int read():一次读取一个字节
* public int read(byte[] b):一次读取一个字节数组 (读取实际的字节数)
* */
public class Text3 {
public static void main(String[] args) throws IOException {
FileInputStream f = new FileInputStream("E:\\\\demo\\\\apple\\\\apple.txt");
int by = 0 ;
//一次读取一个字节
while((by=f.read())!=-1) {
char ch = (char)by;
System.out.print(ch);
}
//释放资源
f.close();
System.out.println("------------------");
//一次读取一个数组
FileInputStream ff = new FileInputStream("E:\\\\demo\\\\apple\\\\apple.txt");
byte[] bys = new byte[1024];
int len = 0;
while((len = ff.read(bys))!=-1) {
System.out.println(new String(bys, 0, len));
}
ff.close();
}
}
package org.westos.IO流博客练习;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* 复制文件
* */
public class Text4 {
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream("E:\\demo\\text\\Begin - 三线の花.mp3");
FileOutputStream fos = new FileOutputStream("E:\\demo\\apple\\复制音乐.mp3");
byte[] bys = new byte[1024];
int len = 0;
while((len = fis.read(bys))!=-1) {
fos.write(bys,0,len);
}
//释放资源,先释放后开启的
fos.close();
fis.close();
}
}