Java学习之IO字节流
2024-10-10 03:25:48
字节流分为FileInputStream 和FileOutputStream
package com.io; import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
/**
* 文件字节流的读取
* @author ganhang
*
*/
public class FileInputStreamDemo {
public static void main(String[] args) {
File file=new File("1.txt");
try {
InputStream is=new FileInputStream(file);
byte [] b= new byte[10];
int len=-1;
StringBuilder sb=new StringBuilder();//存读取的数据
while((len=is.read(b))!=-1){
sb.append(new String(b,0,len));
}
is.close();
System.out.println(sb);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} }
}
package com.io; import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
/**
* 文件字节流的写入
* @author ganhang
*
*/
public class FileOutputStreamDemo {
public static void main(String[] args) {
File file = new File("1.txt");
if (!file.exists()) {
try {
file.createNewFile();//没有则创建文件
} catch (IOException e) {
e.printStackTrace();
}
} else {
try {
OutputStream fos = new FileOutputStream(file, true);//文件末尾添加,不是覆盖
byte[] info = "hello,world".getBytes();
fos.write(info);
fos.close();
System.out.println("写入成功!");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
最新文章
- dataGridViewX和数据库的链接之dataGridViewX1.DataSource = ds.Tables[0];
- (一)MVC5干货篇,目录和路由
- Apache Options Indexes FollowSymLinks详解
- [BZOJ4636]蒟蒻的数列
- Java之美[从菜鸟到高手演练]之JDK动态代理的实现及原理
- 颜色空间转换 cvtColor()[OpenCV 笔记13]
- 开发反模式 - SQL注入
- Response 关于浏览器header的方法
- CSS中垂直居中的方法
- 如何在关闭ssh连接的情况下,让程序继续运行?
- Springboot 部署到linux(二)
- Sqlserver常用基础语句
- os模块(二十)
- 更改具有Foreign key约束的表
- [PHP] 看博客学习观察者模式
- 2018-2019-2 《网络对抗技术》Exp5 MSF基础应用 Week7-8 20165233
- 原生Ajax函数
- openstack kolla 部署---不同的节点采用不同的物理接口
- java 读入文件 FileInputStream
- 基于注解的ssh框架之spring配置文件