int i = 0;
FileInputStream inputStream = new FileInputStream("test.txt");
while(true){
i = inputStream.read();
if(i = -1){
break;
}
System.out.println(i);
}
}
字节流输出文件:
public class Example02{
public void static main(String[] args){
FileOutputStream outputStream = new FileOutputStream("example.txt);
String str = "黑马程序员";
byte[] bytes = str.getBytes();
for(int i = 0 ; i < bytes.length ; i ++){
outputStream.write(bytes[i]);
}
outputStream.close();
}
}
直接用write(byte b)要首先清空原来的文件
要想在源文件后面加,用write(byte b , boolean append)
同时使用FileInputStream和FileOutputStream实现文件的拷贝:
class Example04{
public void static main(String[] args){
FileInputStream in = new FileInputStream("D:\BaiduYunGuanjian");
FileOutputStream out = new FileOutputStream(E:\新建文件夹);
int len ;
long oldTime = System.currentTimeMillis();
while( (len = in.read() ) != -1 ){
out.write(len);
}
long newTime = System.currentTimeMillis();
long time = newTime - oldTime;
in.close();
out.close();
}
}
字节流的缓冲区
复习两个知识点:
int read(byte[] b):从输入流中读取若干字节,把它们保存在参数b指定的字节数组中,返回的整数表示读取数字节
void write(bytes[] b, int off, int len):将指定byte数组中从偏移量off开始的len个字节写入输入流
public class Example05 {
Public void static main(String[] args){
FileInputStream in = new FileInputStream("D:\BaiduYunGuanjia");
FileOutputStream out = new FileOutputStream("D:\新建文件夹")
;
int len ; //这个值是用来记录每次读取的最大字节数的
byte[] b = new byte[1024];
上面的Example05.java就可以简写为:
class Example06{
public void static main(String[] args){
BuffedInputStream in = new BuffedInputStream(new FileInputStream("D:\BaiduYunGuanjia"));
BuffedOutputStream out = new BuffedOutputStream(new FileOutputStream("D:\新建文件夹");
int len = 0 ;
while((len = in.read())!= -1){
out.write(len);
}
in.close();
out.close();
}
}
public class Example11 {
public void static main(Sring[] args){
FileReader reader = new FileReader("Example04.java");
FileWriter writer = new FileWriter("copy.java");
LineNumberReader lbreader = new LineNumberReader(reader);