Java File IO 練習題:把一個檔案夾下的.java檔案複製到另一個檔案夾下的.txt檔案

來源:互聯網
上載者:User

標籤:檔案夾   一個   odi   exist   iter   encoding   readline   writer   不用   

package com.swift;import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStreamReader;import java.io.OutputStreamWriter;import java.io.UnsupportedEncodingException;public class Copy_java_To_txt {    public static void main(String[] args) {        /*         * 把一個檔案夾下的.java檔案複製到另一個檔案夾下的.txt檔案         */        try {            StringBuffer sb = new StringBuffer();            BufferedReader br = new BufferedReader(                    new InputStreamReader(new FileInputStream("e:\\neck\\test.java"), "utf-8"));            String str;            while ((str = br.readLine()) != null) {                System.out.println("從檔案中讀取了一行...");                sb.append(str);                sb.append("\r\n");            }                        System.out.println("檔案讀取到容器成功"+"\r\n"+sb.toString());                        String dir="e:\\apple";            String fileName="test.txt";            File file=new File(dir,fileName);            if(!file.getParentFile().exists()) {                System.out.println(file.getParentFile()+"目錄不存在,即將建立...");                file.getParentFile().mkdirs();            }else {                System.out.println("目錄存在,不用建立...");            }            BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file),"utf-8"));            bw.write(sb.toString());            bw.flush();        } catch (UnsupportedEncodingException e) {            e.printStackTrace();        } catch (FileNotFoundException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }    }}

上面是指定哪個檔案進行複製

下邊是搜尋出所有的以.java結尾的檔案複製到另一個檔案夾並改名

需要用到下邊的兩種列表

list()方法是返回某個目錄下的所有檔案和目錄的檔案名稱,返回的是String數組

listFiles()方法是返回某個目錄下所有檔案和目錄的絕對路徑,返回的是File數組

 

Java File IO 練習題:把一個檔案夾下的.java檔案複製到另一個檔案夾下的.txt檔案

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.