java io流之字节流
字节流
字节流主要是操作byte类型数据,以byte数组为准,主要操作类就是OutputStream、InputStream
字节输出流:OutputStream
OutputStream是整个IO包中字节输出流的最大父类,此类的定义如下:
public abstract class OutputStream extends Object implements Closeable,Flushable
从以上的定义可以发现,此类是一个抽象类,如果想要使用此类的话,则首先必须通过子类实例化对象,那么如果现在要操作的是一个文件,则可以使用:FileOutputStream类。通过向上转型之后,可以为OutputStream实例化
Closeable表示可以关闭的操作,因为程序运行到最后肯定要关闭
Flushable:表示刷新,清空内存中的数据
FileOutputStream类的构造方法如下:
public FileOutputStream(File file) throws FileNotFoundException
以上输出只会进行覆盖,如果要追加的话,请看FileOutputStream类的另一个构造方法;
public FileOutputStream(File file,boolean append)throws FileNotFoundException
在构造方法中,如果将append的值设置为true,则表示在文件的末尾追加内容。
小🌰 :
/**
* 字节流操作,文件内容后面追加内容。而不是覆盖
*/
@Test
public void testFileOutputAppend() throws IOException {
String path = "/Users/xxx/Desktop/study/java/io/字节流";
File file = new File(path + File.separator + "1.txt");
InputStream in = new FileInputStream(file);
int len = 0;
byte[] bytes = new byte[1024];
StringBuilder sb = new StringBuilder("");
while((len = in.read(bytes)) != -1) {
sb.append(new String(bytes,0,len));
}
in.close();
System.out.println("原始报文:\n" + sb.toString());
OutputStream out = new FileOutputStream(file, true);
out.write("我才是追加的".getBytes());
out.flush();
out.close();
}
来自丹枫化雪
浙公网安备 33010602011771号