1. 程式人生 > 其它 >IO流(1)建立檔案

IO流(1)建立檔案

檔案流:檔案在程式中是以流的形式來操作的。

輸入流:資料從資料來源(檔案)到程式(記憶體)的路徑

輸出流:資料從程式(記憶體)到資料來源(檔案)的路徑

建立檔案

  • new File(String pathname)//根據路徑構造一個File物件
  • new File(File parent,String child)//根據父目錄檔案+子目錄構建
  • new File(String parent,String child)//根據父目錄+子路徑構建

createNewFile 建立新檔案

@Test
    //方式1:new File(String pathname)
    public void create01(){
        String filePath
="e:\\news1.txt"; File file = new File(filePath); //File file = new File("e:\\news1.txt"); try { file.createNewFile(); System.out.println("建立成功"); } catch (IOException e) { e.printStackTrace(); } } @Test //方式2:new File(File parent,String child)
//根據父目錄檔案+子路徑構建 //e:\\news2.txt public void create02(){ File parentFile = new File("e:\\");// String fileName = "news2.txt";// File file = new File(parentFile, fileName); try { file.createNewFile(); System.out.println("建立成功"); } catch
(IOException e) { e.printStackTrace(); } } @Test //方式3:new File(String parent,String child)//根據父目錄+子路徑構建 public void create03(){ File parentPath = new File("e:\\"); String fileName = "names3.txt"; File file = new File(parentPath, fileName); try { file.createNewFile(); System.out.println("建立成功"); } catch (IOException e) { e.printStackTrace(); } }

 

獲取檔案資訊

package IO;

import java.io.File;

public class Test {
    public static void main(String[] args) {

    }

    //獲取檔案資訊
    @org.junit.Test
    public void information(){
        File file = new File("e:\\news1.txt");

        //呼叫相印的方法,得到對應的資訊
        System.out.println("檔名字:"+file.getName());
        System.out.println("檔案絕對路徑:"+file.getAbsolutePath());
        System.out.println("檔案父級目錄:"+file.getParent());
        System.out.println("檔案大小(位元組):"+file.length());//一個字母佔一個位元組,中文佔3個
        System.out.println("檔案是否存在:"+file.exists());//T
        System.out.println("是不是一個檔案:"+file.isFile());//T
        System.out.println("是不是一個目錄:"+file.isDirectory());//F
    }
}

建立一級目錄使用mkdir();,建立多級目錄使用mkdirs();

//判斷f:\\demo\\a\\b\\c目錄是否存在,不存在就建立
    @Test
    public void m3(){
        String directoryPath = "f:\\demo\\a\\b\\c";
        File file = new File(directoryPath);
        if (file.exists()){
            System.out.println(directoryPath+"存在");
        }else{
            if(file.mkdirs()){//建立一級目錄使用mkdir();,建立多級目錄使用mkdirs();
                System.out.println(directoryPath+"建立成功");
            }else{
                System.out.println("建立失敗");
            }
        }
    }