使用IO流实现一个简单的小Dome

(一) 在电脑D盘下创建一个文件为HelloWorld.txt文件,判断他是文件还是目录,在创建一个目
录IOTest,之后将HelloWorld.txt移动到IOTest目录下去;之后遍历IOTest这个目录下的文

为了提高代码的安全性,这里所有的异常,我都处理了,而不是抛出,如果想方便的话,可以都抛出。
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;


public class Demo1 {

 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
         File file = new File("C:\Users\junjiejie\Desktop\HelloWorld.txt");
         File file4 = new File("C:\Users\junjiejie\Desktop\Haha.txt");
         FileInputStream fileInputStream = null;
         FileOutputStream fileOutputStream = null;
         File file2 = null ;
         try {
   System.out.println(file.createNewFile());
   System.out.println(file4.createNewFile());
   if (file.isFile()) {
    System.out.println("是文件!");
   }else{
    System.out.println("不是文件!");
   }
   file2 = new File("C:\Users\junjiejie\Desktop\IOTest");
   System.out.println(file2.mkdir());
   File file3 = new File("C:\Users\junjiejie\Desktop\IOTest\HelloWorld.txt");
   System.out.println(file3.createNewFile());
    fileInputStream = new FileInputStream(file);
    fileInputStream = new FileInputStream(file4);
    fileOutputStream = new FileOutputStream(file3);
   byte[] b = new byte[1024];
   while (fileInputStream.read(b) != -1) {
    fileOutputStream.write(b);
    
   }
  } catch (IOException e) {
   // TODO Auto-generated catch block
   throw new RuntimeException(e);
  }finally{
   try {
    fileOutputStream.close();
   } catch (IOException e) {
    // TODO Auto-generated catch block
    throw new RuntimeException(e);
   }
   try {
    fileInputStream.close();
   } catch (IOException e) {
    // TODO Auto-generated catch block
    throw new RuntimeException(e);
   }
   file.delete();
   file4.delete();
   String[] arr= file2.list();
   for (String string : arr) {
    System.out.println(string);
   }
  }
 }

}

原文地址:https://www.cnblogs.com/shen-xiao-jie/p/6137045.html