Java文件字节流
InputStream
一字节
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class TestInputStream {
public static void main(String[] args) throws IOException {
FileInputStream fis=new FileInputStream(new File("D:\\a.txt"));
int count = fis.available();
System.out.println(count);
System.out.println(fis.read());
System.out.println(fis.available());
int buf=0;
while((buf=fis.read())!=-1) {
System.out.println((char)buf);
}
fis.close();
}
}
多字节
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class TestInputStream2 {
public static void main(String[] args) throws IOException {
FileInputStream fis=new FileInputStream("D:\\a.txt");
byte [] buf=new byte[1024];
int len=0;
int i=0;
while((len=fis.read(buf))!=-1) {
i++;
System.out.println(new String(buf,0,len));
}
fis.close();
System.out.println(i);
}
}
OutputStream
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class TestFileOutputStresm {
public static void main(String[] args) throws IOException {
try {
FileOutputStream fos=new FileOutputStream("D:\\a.txt",true);
fos.write(97);
byte[] buf="helloworld".getBytes();
fos.write(buf);
} catch (Exception e) {
e.printStackTrace();
}finally {
FileOutputStream fos = null;
try {
if(fos!=null) {
fos.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
使用字节流实现文件的复制
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class TestFileCopy {
public static void main(String[] args) {
FileInputStream fis=null;
FileOutputStream fos=null;
try {
fis = new FileInputStream("D:\\a.txt");
fos = new FileOutputStream("E:\\target.txt");
byte[] buf=new byte[1024];
int len=0;
while((len=fis.read(buf))!=-1) {
fos.write(buf,0,len);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if(fos!=null) {
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if(fis!=null) {
fis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}