JAVA io流筆記03 位元組流
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());
// }
// 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()));
// }
// }
//}
//正確
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());
}
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()));
}
}
}
}