package FileText;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class FileInputStream03 {
public static void main(String args[]){
try {
Write();
Read();
copy();
CopyDir();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void Read() throws IOException{ //文件读取
//建立联系,File对象
File file = new File("D:/text/dd/text.txt");
//选择流
InputStream input=null;//提升作用域
input = new FileInputStream(file);
byte[] byt = new byte[1024]; //缓冲数组
int len=0; //实际读取长度
while(-1!=(len=input.read(byt))){
String str = new String(byt,0,len);
System.out.println(str);
}
input.close();
}
public static void Write() throws IOException{ //文件写入
String word = "逝者如斯不舍昼夜";
File file = new File("D:/text/dd/text.txt");
OutputStream out = null;
out = new FileOutputStream(file,false); //true为追加文件,false为覆盖文件。不添加默认为false
byte[] byt =word.getBytes(); //字符串转字节数组!
out.write(byt);
out.flush();
out.close();
}
public static void copy() throws IOException{ //文件拷贝
File file = new File("D:/text/dd/text.txt");
File file2 = new File("D:/text/dd/text222.txt");
int len=0;
byte[] byt = new byte[1024];
InputStream input = null;
input = new FileInputStream(file);
FileOutputStream output = new FileOutputStream(file2);
while(-1!=(len=input.read(byt))){
output.write(byt,0,len);
output.flush();
output.close();
}
input.close();
}
public static void CopyDir() throws IOException{
String src="D:/text/dd";
String dest="D:/text/da";
File file = new File(src);
File file2 = new File(dest);
if(file.isDirectory()){
file2 = new File(dest,file.getName());
//注意!!!!!!!!不能把父目录拷贝到子目录中
if(file.getAbsolutePath().contains(file2.getAbsolutePath())){
System.out.println("注意!!!!!!!!不能把父目录拷贝到子目录中");
return;
}
}
CopyDir2(file,file2);
}
public static void CopyDir2(File file ,File file2) throws IOException{
if(file.isFile()){
InputStream input = new FileInputStream(file);
OutputStream output = new FileOutputStream(file2);
byte byt[] = new byte[1024];
int len=0;
if(-1!=(len=input.read(byt))){
output.write(byt, 0, len);
output.flush();
output.close();
input.close();
}
}else if(file.isDirectory()){ //迭代
file2.mkdirs();
for(File temp:file.listFiles()){
CopyDir2(temp,new File(file2,temp.getName()));
}
}
}
}