OutputStream
字节输出流的使用步骤(重点):
1.创建一个FileOutputStream对象,构造方法中传递写入数据的目的地
2.调用FileOutputStream对象中的方法write,把数据写入到文件中
3.释放资源(流使用会占用一定的内存,使用完毕要把内存清空,提供程序效率)
//一次写入一个字节
import java.io.FileOutputStream;
import java.io.IOException;
/*
字节输出流的使用步骤(重点):
1.创建一个FileOutputStream对象,构造方法中传递写入数据的目的地
2.调用FileOutputStream对象中的方法write,把数据写入到文件中
3.释放资源(流使用会占用一定的内存,使用完毕要把内存清空,提供程序效率)
*/
public class OutputStreamDemo01 {
public static void main(String[] args) throws IOException {
//1.创建一个FileOutputStream对象,构造方法中传递写入数据的目的地
FileOutputStream fos = new FileOutputStream("E:\\java\\Utile\\untitled\\src\\cn\\OutputStream\\a.txt");
//2.调用FileOutputStream对象中的方法write,把数据写入到文件中
//public abstract void write(int b);将指定的字节输出流
fos.write(97);//转化为ascll码存放在文件中
//3.释放资源
fos.close();
}
}
//一次写入多个字节
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
/*
一次写入多个字节的方法:
-public void write(byte[] b);将b.length字节从指定的字节数组写入此输出流
-public void write(byte[] b, int off, int len) 将指定 byte 数组中从偏移量 off 开始的 len 个字节写入此输出流。
*/
public class OutputStreamDemo02 {
public static void main(String[] args) throws IOException {
//1.创建一个FileOutputStream对象,构造方法中传递写入数据的目的地
FileOutputStream fos = new FileOutputStream(new File("E:\\java\\Utile\\untitled\\src\\cn\\OutputStream\\b.txt"));
//2.调用FileOutputStream对象中的方法write,把数据写入到文件中
fos.write(48);
fos.write(49);
fos.write(49);
//public void write(byte[] b);将b.length字节从指定的字节数组写入此输出流
//0-127显示Ascll表,第一个如果是负数,两个字组成一个中文显示,查询默认码表(gbk)
byte[] b = {65,54,86,94};
fos.write(b);
//public void write(byte[] b, int off, int len) 将指定 byte 数组中从偏移量 off 开始的 len 个字节写入此输出流。
fos.write(b,1,3);
/*
写入字符串的方法:可以使用string类中的方法把字符串转换成字节数组
byte[] getBytes() 把字符串转换为字节数组
*/
byte[] bytes = "怀德".getBytes();
System.out.println(Arrays.toString(bytes));//转化为字节输出
fos.write(bytes);
//3.释放资源
fos.close();
}
}
//追加和换行输入
import java.io.FileOutputStream;
import java.io.IOException;
public class OutputStreamDemo03 {
public static void main(String[] args) throws IOException {
FileOutputStream fos = new FileOutputStream("E:\\java\\Utile\\untitled\\src\\cn\\OutputStream\\c.txt",true);
for (int i = 0; i < 10; i++) {
fos.write("怀德".getBytes());
fos.write("\r\n".getBytes());//换行,windows用“\r\n”
}
fos.close();
}
}
续写和换行
续写,使用两个参数的构造方法
FileWriter(String fileName,boolean append)
FileWriter(String file,boolean append)
参数:
String fileName,String file,写入数据的目的地
boolean append:续写开关,true,不会创建新的文件覆盖源文件,false:创建新的文件覆盖源文件
换行:windows:\r\n
linux:\n
mac:\r
public class WriterDemo03 {
public static void main(String[] args) throws IOException {
FileWriter fw = new FileWriter("E:\\java\\Utile\\IO\\c.txt",true);
for (int i = 0; i < 5; i++) {
fw.write(97);
fw.write("\r\n");
}
fw.close();
}
}