天天看點

IO架構複習一

IO架構: file類 位元組流 字元流

一 file類的應用:

按照要求列印檔案名 裡面是檔案就遞進tab在列印,依次類推

public class printfMuLu {

public static void main(String[] args) {

printf.bianLi(new File(“e:\a”));

}

}

class printf{

private static int level=0;//此标記量得置于方外,不然每次清零,不會列印tab

public static void bianLi(File file){

//檔案為空,是檔案,或檔案為空直接傳回

if(file==null){

if(file.isFile()||file.listFiles().length==0){

return;

}

}else{

//得到檔案

File[] files = file.listFiles();

//排序

File[] files1 = paixu(files);

//周遊檔案

for(File f:files1){

StringBuffer sb=new StringBuffer();

if(f.isFile()){

sb.append(printfTab(level));

sb.append(f.getName());

}else{

sb.append(printfTab(level));

sb.append(f.getName());

sb.append(“\”);

}

System.out.println(sb.toString());

//是檔案就遞歸

if(f.isDirectory()){

level++;

bianLi(f);

level–;

}

}

}

}

//嵌套檔案個數和對應的列印tab數

public static String printfTab(int number){

StringBuffer sb=new StringBuffer();

for(){

sb.append(“\t”);

}

return sb.toString();

}

//先檔案夾後檔案 這個過程可以省略 一般建立檔案時檔案夾都在上面檔案在下面

public static File[] paixu(File[] file){

ArrayList list=new ArrayList();

for(File f:file){

if(f.isDirectory()){

list.add(f);

}

}

for(File f:file){

if(f.isFile()){

list.add(f);

}

}

File[] files = list.toArray(new File[list.size()]);

return files;

}

}

遞歸思想及 求階乘:

在函數中自己調用自己 一定的有出口

public class DIGUIDemo {

public static void main(String[] args) {

System.out.println(diGui(5));

}

public static int diGui(int number){

//遞歸出口

if(number==1){

return 1;

}

else{

return number*diGui(number-1);

}

}

}

二 位元組流: InputStream和OutputStream 都為抽象類 不能執行個體化

file 和 位元組流 的結合練習 複制檔案夾到指定目錄

public class CopyMuLuDemo {

public static void main(String[] args) {

copyMuLu(new File(“e:\a”),”f:\a”);

}

public static void copyMuLu(File file,String newpath){

File[] files = file.listFiles();

for(File f:files){

if(f.isFile()){

try {

copyFile(f.getPath(),newpath+”\”+f.getName());

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}else{

File file1=new File(newpath+”\”+f.getName());

if(!file1.exists()){

file1.mkdirs();

}

//此處遞歸時newpath變量為的file1的路徑 非f的路徑

copyMuLu(f,file1.getPath());

}

}

}

public static void copyFile(String oldpath,String newPath) throws IOException{

FileInputStream fis=null;

FileOutputStream fos=null;

fis=new FileInputStream(oldpath);

fos=new FileOutputStream(newPath);

byte[] buff=new byte[1024];

int len=0;

while((fis.read(buff)!=-1)){

fos.write(buff, 0, len);

}

fos.close();

fis.close();

}

三 字元流 Reader Writer 類 都為抽象類

位元組流 字元流之間的轉換:

網絡程式設計 tcp/ip 中應用到的:

BufferedReader br=new BufferedReader(new InputStreamReader(socket.getInputStream()));

将socket擷取的位元組輸入流通過InputStreamReader轉換流變成字元流在通過緩沖流BufferedReader進行讀的操作

四:java中輸入與輸出并不是是互相獨立的,有一個類能完成輸入的同時完成輸出,RandomAccessFile

繼續閱讀