java文件操作

        File file = new File("text.txt");
        //判斷文件是否存在
        System.out.println("Does the file exist ? " + file.exists());
        //讀取文件名稱
        System.out.println("The file's name is " + file.getName());
        //讀取文件路徑
        System.out.println("The file's  path is " + file.getPath());
        //讀取文件絕對路徑
        System.err.println("The file's absolute path is " + file.getAbsolutePath());
        //獲取文件父級路徑
        System.err.println("The parent path of the file is " + new File(file.getAbsolutePath()).getParent());
        //讀取文件大小
        System.out.println("The size of the file is " + (float)file.length()/1024);
        //判斷文件是否被隱藏
        System.err.println("Does the file hide?" + file.isHidden());
        //判讀文件是否可讀
        System.out.println("Can the file read?" + file.canRead());
        //判斷文件是否可寫
        System.out.println("Can the file write?" + file.canWrite());
        //判斷文件是否是文件夾
        System.err.println("Is the file directory?" + file.isDirectory());

文件內容的讀取:

                FileInputStream fis = new FileInputStream(file);
                InputStreamReader isr  = new InputStreamReader(fis , "utf-8");
                BufferedReader br = new BufferedReader(isr);
                
                String  line ;
                while((line = br.readLine()) != null ) {
                    System.out.println(line);
                }
                br.close();
                isr.close();
                fis.close();

文件內容的寫入:

File newfile = new File("Newtext.txt");
            FileOutputStream fos  = new FileOutputStream(newfile);
            OutputStreamWriter osw = new OutputStreamWriter(fos , "utf-8");
            BufferedWriter bw = new BufferedWriter(osw);
            
            bw.write("asfasfsdagasgasdgsdga");
            bw.close();
            osw.close();
            fos.close();    

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章