關(guān)于文件File的存取

將文件讀取并寫入一個(gè)文件夾里面的文件中

①生成一個(gè)文件路徑(選擇D盤)

 private static String path = "D:\\file\\"; 

②創(chuàng)建文件的路徑和名稱

private static String filenameTemp;

③創(chuàng)建一個(gè)“寫入文件”的方法:

/**
     * 向文件中寫入內(nèi)容
     * @param filepath 文件路徑與名稱
     * @param new_str  寫入的內(nèi)容
     * @return
     * @throws IOException
     */
    public static boolean writeFileContent(String filepath,String new_str) throws IOException{
        Boolean bool = false;
        String filein = new_str+"\r\n";//新寫入的行,換行
        String temp  = "";
        
        FileInputStream fis = null;
        InputStreamReader isr = null;
        BufferedReader br = null;
        FileOutputStream fos  = null;
        PrintWriter pw = null;
        try {
            File file = new File(filepath);//文件路徑(包括文件名稱)
            //將文件讀入輸入流
            fis = new FileInputStream(file);
            isr = new InputStreamReader(fis);
            br = new BufferedReader(isr);
            StringBuffer buffer = new StringBuffer();
            
            //文件原有內(nèi)容
            for(int i=0;(temp =br.readLine())!=null;i++){
                buffer.append(temp);
                // 行與行之間的分隔符 相當(dāng)于“\n”
                buffer = buffer.append(System.getProperty("line.separator"));
            }
            buffer.append(filein);
            fos = new FileOutputStream(file);
            pw = new PrintWriter(fos);
            pw.write(buffer.toString().toCharArray());
            pw.flush();
            bool = true;
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }finally {
            //不要忘記關(guān)閉
            if (pw != null) {
                pw.close();
            }
            if (fos != null) {
                fos.close();
            }
            if (br != null) {
                br.close();
            }
            if (isr != null) {
                isr.close();
            }
            if (fis != null) {
                fis.close();
            }
        }
        return bool;
    }

④創(chuàng)建一個(gè)“創(chuàng)建文件的方法”,并且引用“寫入文件”的方法。

public static boolean createFile(String fileName,String filecontent){
        Boolean bool = false;
        filenameTemp = path+fileName+".txt";//文件路徑+名稱+文件類型
        File file = new File(filenameTemp);//new一個(gè)文件對(duì)象
        try {
            //如果文件不存在,則創(chuàng)建新的文件
            if(!file.exists()){
                file.createNewFile();//創(chuàng)建一個(gè)新的文件目錄。
                bool = true;
                System.out.println("文件創(chuàng)建成功,文件名是:"+filenameTemp);
                //調(diào)用writeFileContent()方法,創(chuàng)建文件成功后,寫入內(nèi)容到文件里
                writeFileContent(filenameTemp, filecontent);
            }else {
                bool = true;//開關(guān)打開。
                System.out.println("文件已存在!");
                //調(diào)用writeFileContent()方法,繼續(xù)寫入內(nèi)容到文件里
                writeFileContent(filenameTemp, filecontent);
            }
        } catch (Exception e) {
            bool = false;
            e.printStackTrace();
        }       
        return bool;
    }

⑤引用“createFile”方法就可以寫入文件!

以下是總結(jié):


public class Test2 {
    //生成文件路徑
    private static String path = "D:\\file\\";    
    //文件路徑+名稱
    private static String filenameTemp;
    /**
     * 創(chuàng)建文件
     * @param fileName  文件名稱
     * @param filecontent   文件內(nèi)容
     * @return  是否創(chuàng)建成功,成功則返回true
     */
    public static boolean createFile(String fileName,String filecontent){
        Boolean bool = false;
        filenameTemp = path+fileName+".txt";//文件路徑+名稱+文件類型
        File file = new File(filenameTemp);//new一個(gè)文件對(duì)象
        try {
            //如果文件不存在,則創(chuàng)建新的文件
            if(!file.exists()){
                file.createNewFile();//創(chuàng)建一個(gè)新的文件目錄。
                bool = true;
                System.out.println("文件創(chuàng)建成功,文件名是:"+filenameTemp);
                //調(diào)用writeFileContent()方法,創(chuàng)建文件成功后,寫入內(nèi)容到文件里
                writeFileContent(filenameTemp, filecontent);
            }else {
                bool = true;//開關(guān)打開。
                System.out.println("文件已存在!");
                //調(diào)用writeFileContent()方法,繼續(xù)寫入內(nèi)容到文件里
                writeFileContent(filenameTemp, filecontent);
            }
        } catch (Exception e) {
            bool = false;
            e.printStackTrace();
        }       
        return bool;
    }
    
    /**
     * 向文件中寫入內(nèi)容
     * @param filepath 文件路徑與名稱
     * @param new_str  寫入的內(nèi)容
     * @return
     * @throws IOException
     */
    public static boolean writeFileContent(String filepath,String new_str) throws IOException{
        Boolean bool = false;
        String filein = new_str+"\r\n";//新寫入的行,換行
        String temp  = "";
        
        FileInputStream fis = null;
        InputStreamReader isr = null;
        BufferedReader br = null;
        FileOutputStream fos  = null;
        PrintWriter pw = null;
        try {
            File file = new File(filepath);//文件路徑(包括文件名稱)
            //將文件讀入輸入流
            fis = new FileInputStream(file);
            isr = new InputStreamReader(fis);
            br = new BufferedReader(isr);
            StringBuffer buffer = new StringBuffer();
            
            //文件原有內(nèi)容
            for(int i=0;(temp =br.readLine())!=null;i++){
                buffer.append(temp);
                // 行與行之間的分隔符 相當(dāng)于“\n”
                buffer = buffer.append(System.getProperty("line.separator"));
            }
            buffer.append(filein);
            fos = new FileOutputStream(file);
            pw = new PrintWriter(fos);
            pw.write(buffer.toString().toCharArray());
            pw.flush();
            bool = true;
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }finally {
            //不要忘記關(guān)閉
            if (pw != null) {
                pw.close();
            }
            if (fos != null) {
                fos.close();
            }
            if (br != null) {
                br.close();
            }
            if (isr != null) {
                isr.close();
            }
            if (fis != null) {
                fis.close();
            }
        }
        return bool;
    }
    
    /**
     * 刪除文件
     * @param fileName 文件名稱
     * @return
     */
    public static boolean delFile(String fileName){
        Boolean bool = false;
        filenameTemp = path+fileName+".txt";
        File file  = new File(filenameTemp);
        try {
            if(file.exists()){
                file.delete();
                bool = true;
            }
        } catch (Exception e) {
            // TODO: handle exception
        }
        return bool;
    }
    public static void main(String[] args) {
        UUID uuid = UUID.randomUUID();
        //分開用uuID把數(shù)據(jù)分開
        createFile(uuid+"myfile", "我的夢(mèng)說別停留等待,就讓光芒折射淚濕的瞳孔,映出心中最想擁有的彩虹,帶我奔向那片有你的天空,因?yàn)槟闶俏业膲?mèng) 我的夢(mèng)"); 
        //總共的數(shù)據(jù)
        createFile("myfile", "");
        
    }   
    
}


最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 相關(guān)鏈接:https://developer.apple.com/library/archive/document...
    ngugg閱讀 440評(píng)論 0 0
  • NTFS設(shè)計(jì)目標(biāo)和特性 1. NTFS設(shè)計(jì)目標(biāo) NTFS設(shè)計(jì)目標(biāo)就包含作為一個(gè)企業(yè)級(jí)文件系統(tǒng)所需要的各種特性: 1...
    江南野梔子閱讀 2,083評(píng)論 0 0
  • 關(guān)于Mongodb的全面總結(jié) MongoDB的內(nèi)部構(gòu)造《MongoDB The Definitive Guide》...
    中v中閱讀 32,316評(píng)論 2 89
  • Class Overview (類概述) 一個(gè)由路徑名確定文件系統(tǒng)實(shí)體的“抽象”表示。這個(gè)路徑名可能是絕對(duì)路徑(相...
    叁點(diǎn)水閱讀 504評(píng)論 0 0
  • ■導(dǎo)讀:青春像大理啤酒的泡沫一樣,帶走每一個(gè)男人的風(fēng)花雪月?!⒘恋脑铝?兄弟?。榱松钗覀冞h(yuǎn)離農(nóng)村,在他鄉(xiāng)揮...
    阿亮的月亮閱讀 416評(píng)論 7 2

友情鏈接更多精彩內(nèi)容