您的位置:首页 > 编程语言 > Java开发

Java学习之IO字节流

2016-01-23 22:57 411 查看
字节流分为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();
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: