字节行文件流
- FileInputStream 字节型输入流
- FileOutputStream 字节型输出流
常用的构造函数
- FileInputStream fis = new FileInputStream(String path);
- FileInputStream fis = new FileInputStream(File file);
- 传入的参数是为了将产生的file对象与真实硬盘上的文件产生一个映射
读取方法每次读取一个字节
public static void main(String[] args){
File file = new File(path);
FileInputStream fis = null;
try{
int code = fis.read();
while(code != -1){
System.out.print((char)code);
code = fis.read();
}
}catch(IOException e){
e.printStackTrace();
}finally{
try{
if(fis!=null)fis.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
每次读取多个字节
public static void main(String[] args){
File file = new File(path);
FileInputStream fis = null;
byte[] bytes = new byte[5];
try{
int count = fis.read(bytes);
while(count != -1){
String str = new String(bytes,0,count);
code = fis.read(bytes);
}
}catch(IOException e){
e.printStackTrace();
}finally{
try{
if(fis!=null)fis.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
字节行输入流与输出流产生在哪里?
- 首先是file对象与真实磁盘上的文件产生一个映射关系
- 输入流或者输出流与file对象直接架设了一个管道,数据在这个管道中流通
流的写入
public static void main(String[] args){
File file = new File(path);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file,true);
fos.write(97);
fos.write(97);
fos.write(97);
<!--可以传入一个字符串然后转化成byte数组,方便写入
String str = "12345678";
byte[] strbyte = str.getBytes();
fos.write(strbyte);
-->
fos.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(fos != null) fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
利用上面的知识做一个文件的复制
public static void main(String[] args){
File source = new File("要拷贝的文件路径");
File target = new File("拷贝到的目标路径");
FileInputStream fis = null;
FileOutputStream fos = null;
bytep[] bytes = new byte[5];
try{
fis = new FileInputStream(source);
fos = new FileOutputStream(target);
int count = fis.read(bytes);
while(count != -1) {
<!--在这里可以做文件的加密以及特殊处理-->
fos.write(bytes,0,count);
fos.flush();
count = fis.read(bytes);
}
}catch(IOException e){
e.printStackTrace();
}finally{
try{
if(fis!=null) fis.close();
}catch(IOException e){
e.printStackTrace();
}
try{
if(fos!=null) fos.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
文件夹的复制包含里面的文件
public static void copyFile(File file, String path) throws IOException{
String absPath = file.getAbsolutePath();
int index = absPath.lastIndexOf("/");
String newPath = path+absPath.subString(index);
File newFile = new File(newPath);
File[] files = file.listFiles();
if(files != null){
newFile.mkdir();
if(files.length>0){
for(File f:files){
copyFile(f,newPath)
}
}
}else{
FileInputStream fis = new FileInputStream(file);
FileOutputStream fos = new FileOutputStream(newFile);
byte[] bytes = new byte[1024];
int count = fis.read(bytes);
while(count != -1){
fos.write(bytes,0,count);
fos.flush();
count = fis.read(bytes);
}
fis.close();
fos.close();
}
}