字节输出流【OutputStream】
FileOutputStream类
写入数据到文件
写多个字节到文件
public class Demo2 {
public static void main(String[] args) throws IOException {
FileOutputStream fos = new FileOutputStream(new File("/Users/wym/b.txt"));
续写和换行
public class Demo3 {
public static void main(String[] args) throws IOException {
FileOutputStream fos = new FileOutputStream("/Users/wym/b.txt",true);
for(int i = 0;i < 10;i++){
fos.write("你好".getBytes());
fos.write("\r".getBytes());
}
fos.close();
}
}
字节输入流【InputStream】
FileInputStream类
读取字节数据
public class Demo1 {
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream("/Users/wym/b.txt");
int len;
while((len = fis.read()) != -1){
System.out.println(len);
}
fis.close();
}
}
读取多个字节
public class Demo2 {
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream("/Users/wym/b.txt");
byte[] bytes = new byte[1024];
int len;
while((len = fis.read(bytes)) != -1){
System.out.println(new String(bytes,0,len));
}
fis.close();
}
}
文件复制练习
public class Copy {
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream("/Users/wym/Downloads/默认头像.png");
FileOutputStream fos = new FileOutputStream("/Users/wym/默认头像.png");
byte[] bytes = new byte[1024];
int len;
while((len = fis.read(bytes)) != -1){
fos.write(bytes,0,len);
}
fos.close();
fis.close();
}
}