转载请注明出处:文件I/O流读写_Mr_Leixiansheng的博客-CSDN博客
步骤:
1、创建输入/输出流对象
2、设置好读写路径
3、设置一个缓存byte[] buffer、一个计数值int n
4、开始读写
5、关闭流
注意事项:
1、读写操作后一定要关闭流
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class Text {
public static void main(String[] args) {
// TODO Auto-generated method stub
//创建读写对象
FileInputStream fis = null;
FileOutputStream fos = null;
try {
//设置读写路径
fis = new FileInputStream(new File("d:\\text.txt"));
fos = new FileOutputStream(new File("d:\\text2.txt")); //没有此文件系统会自动创建
int n = 0;
byte[] buffer = new byte[512];
while((n=fis.read(buffer)) != -1) {
//显示读取内容
// String str = new String(buffer, 0, n);
// System.out.println(str);
fos.write(buffer, 0, n);
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally {
try {
//关闭流
fis.close();
fos.close();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
}
安卓文件安存储(简介保存图片为例)
private void savePic(byte[] bytes) {
File dir = new File(Environment.getExternalStorageDirectory().getAbsoluteFile(), "/test");//指定保存文件夹
if (!dir.exists()) {
dir.mkdirs();
}
File fileName = new File(dir, "pic.jpeg");//文件保存位置和文件名
try {
fileName.createNewFile();
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(fileName));
bos.write(bytes);
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}