16文件與流

<pre>

什么是文件?

文件可認(rèn)為是相關(guān)記錄或放在一起的數(shù)據(jù)的集合

文件一般存儲(chǔ)在哪里?

image

JAVA程序如何訪問文件屬性?

java.io.File 類

File類訪問文件屬性

image

JAVA中的文件及目錄處理類

在Java中提供了操作文件及目錄(即我們所說的文件夾)類File。有以下幾點(diǎn)注意事項(xiàng):

(1)不論是文件還是目錄都使用File類操作;

(2)File類只提供操作文件及目錄的方法,并不能訪問文件的內(nèi)容,所以他描述的是文件本身的屬性;

(3)如果要訪問文件本身,用到了我們下面要學(xué)習(xí)的IO流.

一:構(gòu)造方法

File 文件名/目錄名 = new File("文字路徑字符串");

在Java中提供了幾種創(chuàng)建文件及目錄的構(gòu)造方法,但大體上都是用參數(shù)中的文字路徑字符串來創(chuàng)建。

二:一般方法

(1)文件檢測相關(guān)方法

boolean isDirectory():判斷File對(duì)象是不是目錄

boolean isFile():判斷File對(duì)象是不是文件

boolean exists():判斷File對(duì)象對(duì)應(yīng)的文件或目錄是不是存在

(2)文件操作的相關(guān)方法

boolean createNewFile():路徑名指定的文件不存在時(shí),創(chuàng)建一個(gè)新的空文件

boolean delete():刪除File對(duì)象對(duì)應(yīng)的文件或目錄

(3)目錄操作的相關(guān)方法

boolean mkdir():單層創(chuàng)建空文件夾

boolean mkdirs():多層創(chuàng)建文件夾

File[] listFiles():返回File對(duì)象表示的路徑下的所有文件對(duì)象數(shù)組

(4)訪問文件相關(guān)方法

String getName():獲得文件或目錄的名字

String getAbsolutePath():獲得文件目錄的絕對(duì)路徑

String getParent():獲得對(duì)象對(duì)應(yīng)的目錄的父級(jí)目錄

long lastModified():獲得文件或目錄的最后修改時(shí)間

long length() :獲得文件內(nèi)容的長度

目錄的創(chuàng)建

public class MyFile {
  public static void main(String[] args) {
      //創(chuàng)建一個(gè)目錄
      File file1 = new File("d:\\test");
      //判斷對(duì)象是不是目錄
      System.out.println("是目錄嗎?"+file1.isDirectory());
      //判斷對(duì)象是不是文件
      System.out.println("是文件嗎?"+file1.isFile());
      //獲得目錄名
      System.out.println("名稱:"+file1.getName());
      //獲得相對(duì)路徑
      System.out.println("相對(duì)路徑:"+file1.getPath());
      //獲得絕對(duì)路徑
      System.out.println("絕對(duì)路徑:"+file1.getAbsolutePath());
      //最后修改時(shí)間
      System.out.println("修改時(shí)間:"+file1.lastModified());
      //文件大小
      System.out.println("文件大小:"+file1.length());
  }
}

程序首次運(yùn)行結(jié)果:

是目錄嗎?false
是文件嗎?false
名稱:test
相對(duì)路徑:d:\test
絕對(duì)路徑:d:\test
修改時(shí)間:0
文件大小:0

file1對(duì)象是目錄啊,怎么在判斷“是不是目錄”時(shí)輸出了false呢?這是因?yàn)橹皇莿?chuàng)建了代表他是目錄的對(duì)象,還沒有真正的創(chuàng)建,這時(shí)候要用到mkdirs()方法,如下:

public class MyFile {
    public static void main(String[] args) {
        //創(chuàng)建一個(gè)目錄
        File file1 = new File("d:\\test\\test");
        file1.mkdirs();//創(chuàng)建了多級(jí)目錄
        //判斷對(duì)象是不是目錄
        System.out.println("是目錄嗎?"+file1.isDirectory());     
    }
}

文件的創(chuàng)建

public class MyFile {
    public static void main(String[] args) {
        //創(chuàng)建一個(gè)文件
        File file1 = new File("d:\\a.txt");

        //判斷對(duì)象是不是文件
        System.out.println("是文件嗎?"+file1.isFile());  
    }
}

首次運(yùn)行結(jié)果:

是文件嗎?false

同樣會(huì)發(fā)現(xiàn)類似于上面的問題,這是因?yàn)橹皇谴砹艘粋€(gè)文件對(duì)象,并沒有真正的創(chuàng)建,要用到createNewFile()方法,如下

public class MyFile {
    public static void main(String[] args) {
        //創(chuàng)建一個(gè)文件對(duì)象
        File file1 = new File("d:\\a.txt");
        try {
            file1.createNewFile();//創(chuàng)建真正的文件
        } catch (IOException e) {
            e.printStackTrace();
        }
        //判斷對(duì)象是不是文件
        System.out.println("是文件嗎?"+file1.isFile());  
    }
}

文件夾與文件的創(chuàng)建目錄

文件時(shí)存放在文件夾下的,所以應(yīng)該先創(chuàng)建文件夾,后創(chuàng)建文件,如下:

public class MyFile {
    public static void main(String[] args) {
        //代表一個(gè)文件夾對(duì)象,單層的創(chuàng)建
        File f3 = new File("d:/test");
        File f4 = new File("d:/test/a.txt");
        f3.mkdir();//先創(chuàng)建文件夾,才能在文件夾下創(chuàng)建文件
        try {
            f4.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }

        //代表一個(gè)文件夾對(duì)象,多層的創(chuàng)建
        File f5= new File("d:/test/test/test");
        File f6 = new File("d:/test/test/test/a.txt");
        f5.mkdirs();//多層創(chuàng)建
        try {
            f6.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

運(yùn)行結(jié)果為,在D磁盤的test文件夾下有一個(gè)a.txt,在D磁盤的test/test/test下有一個(gè)a.txt文件。

編程:判斷是不是有這個(gè)文件,若有則刪除,沒有則創(chuàng)建

public class TestFileCreatAndDele {
    public static void main(String[] args) {
        File f1 = new File("d:/a.txt");
        if(f1.exists()){//文件在嗎
            f1.delete();//在就刪除
        }else{//不在
            try {
                f1.createNewFile();//就重新創(chuàng)建
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

文件的逐層讀取

File的listFiles()只能列出當(dāng)前文件夾下的文件及目錄,那么其子目錄下的文件及目錄該如何獲取呢?解決的辦法有很多,在這運(yùn)用遞歸解決.

//逐層獲取文件及目錄
public class TestFindFile {
    public static void openAll(File f) {// 遞歸的實(shí)現(xiàn)
        File[] arr = f.listFiles();// 先列出當(dāng)前文件夾下的文件及目錄
        for (File ff : arr) {
            if (ff.isDirectory()) {// 列出的東西是目錄嗎
                System.out.println(ff.getName());
                openAll(ff);// 是就繼續(xù)獲得子文件夾,執(zhí)行操作
            } else {
                // 不是就把文件名輸出
                System.out.println(ff.getName());
            }
        }
    }
    public static void main(String[] args) {
        File file = new File("d:/test");// 創(chuàng)建目錄對(duì)象
        openAll(file);// 打開目錄下的所有文件及文件夾
    }
}

如何讀寫文件?

通過流來讀寫文件

流是指一連串流動(dòng)的字符,是以先進(jìn)先出方式發(fā)送信息的通道

image

輸入/輸出流與數(shù)據(jù)源

image

Java流的分類

image

小重點(diǎn)

package com.company;

import java.io.*;
import java.util.Date;

/**
 * Created by ttc on 2018/1/12.
 */
public class FileDemo {
    public static void main(String[] args) throws IOException {

        File file = new File("d:/hello.txt");
        FileInputStream fileInputStream = new FileInputStream(file);

        //先讀一個(gè)字節(jié) 
        int n = fileInputStream.read();
        byte[] buffer = new byte[2000];
        int index = 0;
        while (n != -1)
        {
            buffer[index] = (byte) n;
            index++;
            System.out.println(Integer.toHexString(n));
            n = fileInputStream.read();//嘗試讀下一個(gè)字節(jié)
        }
        System.out.println("讀完了");

        String string = new String(buffer, 0, index);// String(byte[] buffer, int offset, int len);可以將字節(jié)數(shù)組轉(zhuǎn)變成字符串
        System.out.println(string);

        //

//        int n;
//        int count = 0;
//        while ((n=fileInputStream.read())!=-1)
//        {
//            System.out.println(Integer.toHexString(n));
//            count++;
//        }
//
//        System.out.println(count);
        fileInputStream.close();
    }
}

文本文件的讀寫

  • 用FileInputStream和FileOutputStream讀寫文本文件

  • 用BufferedReader和BufferedWriter讀寫文本文件

二進(jìn)制文件的讀寫

  • 使用DataInputStream和DataOutputStream讀寫二進(jìn)制文件

使用FileInputStream 讀文本文件

image

InputStream類常用方法
int read( )
int read(byte[] b)
int read(byte[] b,int off,int len)
void close( )
子類FileInputStream常用的構(gòu)造方法
FileInputStream(File file)
FileInputStream(String name)

一個(gè)一個(gè)字節(jié)的讀

public static void main(String[] args) throws IOException {
    // write your code here
        File file = new File("d:/我的青春誰做主.txt");
        FileInputStream fileInputStream = new FileInputStream(file);

        byte[] buffer = new byte[100];//保存從磁盤讀到的字節(jié)
        int index = 0;

        int content = fileInputStream.read();//讀文件中的一個(gè)字節(jié)

        while (content != -1)//文件中還有內(nèi)容,沒有讀完
        {
            buffer[index] = (byte)content;
            index++;

            //讀文件中的下一個(gè)字節(jié)
            content = fileInputStream.read();
        }

        //此時(shí)buffer數(shù)組中讀到了文件的所有字節(jié)

        String string = new String(buffer,0, index);

        System.out.println(string);
    }

一批一批的讀

public static void main(String[] args) throws IOException {
        // write your code here

        File file = new File("d:/我的青春誰做主.txt");
        FileInputStream fileInputStream = new FileInputStream(file);

        byte[] buffer = new byte[SIZE];//保存從磁盤讀到的字節(jié)


        int len = fileInputStream.read(buffer);//第一次讀文件中的100個(gè)字節(jié)
        while (len != -1)
        {
            String string = new String(buffer,0, len);
            System.out.println(string);
            //讀下一批字節(jié)
            len = fileInputStream.read(buffer);
        }
    }
import java.io.File;  
import java.io.FileInputStream;  
import java.io.FileNotFoundException;  
import java.io.IOException;  
import java.util.Arrays;  

public class FileInputStreamDemo1 {  

    private static final int SIZE = 4096;  

    public static void main(String[] args) throws IOException {  

        /* 
         * 將已有文件的數(shù)據(jù)讀取出來 
         * 既然是讀,使用InputStream 
         * 而且是要操作文件。FileInputStream 
         *  
         */  

        //為了確保文件一定在之前是存在的,將字符串路徑封裝成File對(duì)象  
        File file = new File("tempfile\\fos.txt");  
        if(!file.exists()){  
            throw new RuntimeException("要讀取的文件不存在");  
        }  

        //創(chuàng)建文件字節(jié)讀取流對(duì)象時(shí),必須明確與之關(guān)聯(lián)的數(shù)據(jù)源。  
        FileInputStream fis = new FileInputStream(file);  

        //調(diào)用讀取流對(duì)象的讀取方法  
        //1.read()返回的是讀取到的字節(jié)  
        //2.read(byte[] b)返回的是讀取到的字節(jié)個(gè)數(shù)  

        //1\.   
//      int by=0;  
//      while((by=fis.read())!=-1){  
//          System.out.println(by);  
//      }  

        //2\.  
//      byte[] buf = new byte[3];  
//      int len = fis.read(buf);//len記錄的是往字節(jié)數(shù)組里存儲(chǔ)的字節(jié)個(gè)數(shù)  

//      System.out.println(len+"...."+new String(buf,0,len));//轉(zhuǎn)成字符串  
//        
//      int len1 = fis.read(buf);  
//      System.out.println(len1+"...."+new String(buf,0,len1));  

        //創(chuàng)建一個(gè)字節(jié)數(shù)組,定義len記錄長度  
        int len = 0;  
        byte[] buf = new byte[SIZE];  
        while((len=fis.read(buf))!=-1){  
            System.out.println(new String(buf,0,len));  
        }  

        //關(guān)資源  
        fis.close();  
    }  

}  

使用FileOutputStream 寫文本文件

image
public class FileOutputStreamTest {

    public static void main(String[] args) {
        FileOutputStream fos=null;
         try {
             String str ="好好學(xué)習(xí)Java";
             byte[] words  = str.getBytes();
             fos = new FileOutputStream("D:\\myDoc\\hello.txt");
             fos.write(words, 0, words.length);
             System.out.println("hello文件已更新!");
          }catch (IOException obj) {
              System.out.println("創(chuàng)建文件時(shí)出錯(cuò)!");
          }finally{
              try{
                  if(fos!=null)
                      fos.close();
              }catch (IOException e) {
                 e.printStackTrace();
              }
          }
    }
}

OutputStream類常用方法
void write(int c)
void write(byte[] buf)
void write(byte[] b,int off,int len)
void close( )
子類FileOutputStream常用的構(gòu)造方法
FileOutputStream (File file)
FileOutputStream(String name)
FileOutputStream(String name,boolean append)

1、前兩種構(gòu)造方法在向文件寫數(shù)據(jù)時(shí)將覆蓋文件中原有的內(nèi)容

2、創(chuàng)建FileOutputStream實(shí)例時(shí),如果相應(yīng)的文件并不存在,則會(huì)自動(dòng)創(chuàng)建一個(gè)空的文件

復(fù)制文件內(nèi)容

文件“我的青春誰做主.txt”位于D盤根目錄下,要求將此文件的內(nèi)容復(fù)制到

C:\myFile\my Prime.txt中

實(shí)現(xiàn)思路

  1. 創(chuàng)建文件“D:\我的青春誰做主.txt”并自行輸入內(nèi)容
  2. 創(chuàng)建C:\myFile的目錄。
  3. 創(chuàng)建輸入流FileInputStream對(duì)象,負(fù)責(zé)對(duì)D:\我的青春誰做主.txt文件的讀取。
  4. 創(chuàng)建輸出流FileOutputStream對(duì)象,負(fù)責(zé)將文件內(nèi)容寫入到C:\myFile\my Prime.txt中。
  5. 創(chuàng)建中轉(zhuǎn)站數(shù)組words,存放每次讀取的內(nèi)容。
  6. 通過循環(huán)實(shí)現(xiàn)文件讀寫。
  7. 關(guān)閉輸入流、輸出流
    l老師帶著做
public static void main(String[] args) throws IOException {
        //創(chuàng)建E:\myFile的目錄。

        File folder = new File("E:\\myFile");
        if (!folder.exists())//判斷目錄是否存在
        {
            folder.mkdirs();//如果不存在,創(chuàng)建該目錄
        }

        //創(chuàng)建輸入流
        File fileInput = new File("d:/b.rar");
        FileInputStream fileInputStream = new FileInputStream(fileInput);
        //創(chuàng)建輸出流
        FileOutputStream fileOutputStream = new FileOutputStream("E:\\myFile\\c.rar");
        //創(chuàng)建中轉(zhuǎn)站數(shù)組buffer,存放每次讀取的內(nèi)容
        byte[] buffer = new byte[1000];

        //從fileInputStream(d:/我的青春誰做主.txt)中讀100個(gè)字節(jié)到buffer中
        int length = fileInputStream.read(buffer);

        int count = 0;
        while (length != -1) //這次讀到了至少一個(gè)字節(jié)
        {
            System.out.println(length);
            //將buffer中內(nèi)容寫入到輸出流(E:\myFile\myPrime.txt)
            fileOutputStream.write(buffer,0,length);

            //繼續(xù)從輸入流中讀取下一批字節(jié)
            length = fileInputStream.read(buffer);
            count++;
        }
        System.out.println(count);

        fileInputStream.close();
        fileOutputStream.close();
    }
public class InputAndOutputFile {
    public static void main(String[] args) {
        FileInputStream fis=null;
        FileOutputStream fos=null;
        try {
            //1、創(chuàng)建輸入流對(duì),負(fù)責(zé)讀取D:/ 我的青春誰做主.txt文件
            fis = new FileInputStream("D:/我的青春誰做主.txt");
            //2、創(chuàng)建輸出流對(duì)象
            fos = new FileOutputStream("C:/myFile/myPrime.txt",true);
            //3、創(chuàng)建中轉(zhuǎn)站數(shù)組,存放每次讀取的內(nèi)容
            byte[] words=new byte[1024];
            //4、通過循環(huán)實(shí)現(xiàn)文件讀取
            while((fis.read())!=-1){
                fis.read(words);
                fos.write(words, 0, words.length);
            }
            System.out.println("復(fù)制完成,請(qǐng)查看文件!");      
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            //5、關(guān)閉流
            try {
                if(fos!=null
                    fos.close();
                if(fis!=null)
                    fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
}

使用字符流讀寫文件

使用FileReader讀取文件

老師帶著做

public static void main(String[] args) throws IOException {
        //
        FileReader fileReader = new FileReader("D:/我的青春誰做主.txt");

        char[] array = new char[100];
        int length = fileReader.read(array);
        StringBuilder sb = new StringBuilder();
        while (length != -1)
        {
            sb.append(array);
            length = fileReader.read(array);
        }

        System.out.println(sb.toString());
        fileReader.close();

    }
public class FileReaderTest {

    /**
     * @param args
     */
    public static void main(String[] args) {
        //創(chuàng)建 FileReader對(duì)象對(duì)象.
        Reader fr=null;
        StringBuffer sbf=null;
        try {
            fr = new FileReader("D:\\myDoc\\簡介.txt");
            char ch[]=new char[1024];  //創(chuàng)建字符數(shù)組作為中轉(zhuǎn)站
            sbf=new StringBuffer();
            int length=fr.read(ch);  //將字符讀入數(shù)組
            //循環(huán)讀取并追加字符
            while ((length!= -1)) { 
                sbf.append(ch);   //追加到字符串
                length=fr.read();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally{
            try {
                if(fr!=null)
                    fr.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        System.out.println(sbf.toString());
    }

}

BufferedReader類

如何提高字符流讀取文本文件的效率?

使用FileReader類與BufferedReader類

BufferedReader類是Reader類的子類

BufferedReader類帶有緩沖區(qū)

按行讀取內(nèi)容的readLine()方法

image
public static void main(String[] args) throws IOException {
        FileReader fileReader = new FileReader("D:/我的青春誰做主.txt");

        BufferedReader bufferedReader = new BufferedReader(fileReader);

        String strContent = bufferedReader.readLine();
        StringBuilder sb = new StringBuilder();
        while (strContent != null)
        {
            sb.append(strContent);
            sb.append("\n");
            sb.append("\r");
            strContent = bufferedReader.readLine();
        }

        System.out.println(sb.toString());
        fileReader.close();
        bufferedReader.close();
    }
public class BufferedReaderTest {

    /**
     * @param args
     */
    public static void main(String[] args) {
        FileReader fr=null;
        BufferedReader br=null;
        try {
            //創(chuàng)建一個(gè)FileReader對(duì)象
            fr=new FileReader("D:\\myDoc\\hello.txt"); 
            //創(chuàng)建一個(gè)BufferedReader 對(duì)象
            br=new BufferedReader(fr); 
            //讀取一行數(shù)據(jù) 
            String line=br.readLine();
            while(line!=null){ 
                System.out.println(line);
                line=br.readLine(); 
            }
        }catch(IOException e){
                System.out.println("文件不存在!");
        }finally{
             try {
                 //關(guān)閉 流
                if(br!=null)
                    br.close();
                if(fr!=null)
                    fr.close(); 
             } catch (IOException e) {
                e.printStackTrace();
             }
        }
    }
}

使用FileWriter寫文件

public class WriterFiletTest {

    /**
     * @param args
     */
    public static void main(String[] args) {
        Writer fw=null;
        try {
              //創(chuàng)建一個(gè)FileWriter對(duì)象
              fw=new FileWriter("D:\\myDoc\\簡介.txt"); 
              //寫入信息
              fw.write("我熱愛我的團(tuán)隊(duì)!");            
              fw.flush();  //刷新緩沖區(qū)

        }catch(IOException e){
              System.out.println("文件不存在!");
        }finally{
            try {
                if(fw!=null)
                    fw.close();  //關(guān)閉流
             } catch (IOException e) {
                e.printStackTrace();
             }
        }
    }

}

如何提高字符流寫文本文件的效率?

使用FileWriter類與BufferedWriter類

BufferedWriter類是Writer類的子類

BufferedWriter類帶有緩沖區(qū)

image
public class BufferedWriterTest {
    public static void main(String[] args) {
        FileWriter fw=null;
        BufferedWriter bw=null;
        FileReader fr=null;
        BufferedReader br=null;
        try {
           //創(chuàng)建一個(gè)FileWriter 對(duì)象
           fw=new FileWriter("D:\\myDoc\\hello.txt"); 
           //創(chuàng)建一個(gè)BufferedWriter 對(duì)象
           bw=new BufferedWriter(fw); 
           bw.write("大家好!"); 
           bw.write("我正在學(xué)習(xí)BufferedWriter。"); 
           bw.newLine(); 
           bw.write("請(qǐng)多多指教!"); 
           bw.newLine();               
           bw.flush();

           //讀取文件內(nèi)容
            fr=new FileReader("D:\\myDoc\\hello.txt"); 
            br=new BufferedReader(fr); 
            String line=br.readLine();
            while(line!=null){ 
                System.out.println(line);
                line=br.readLine(); 
            }

            fr.close(); 
           }catch(IOException e){
                System.out.println("文件不存在!");
           }finally{
               try{
                   if(fw!=null)
                       fw.close();
                   if(br!=null)
                       br.close();
                   if(fr!=null)
                       fr.close();  
               }catch(IOException ex){
                    ex.printStackTrace();
               }
           }
    }
}

練習(xí)

格式模版保存在文本文件pet.template中,內(nèi)容如下:

您好!

我的名字是{name},我是一只{type}。

我的主人是{master}。

其中{name}、{type}、{master}是需要替換的內(nèi)容,現(xiàn)在要求按照模板格式保存寵物數(shù)據(jù)到文本文件,即把{name}、{type}、{master}替換為具體的寵物信息,該如何實(shí)現(xiàn)呢?

實(shí)現(xiàn)思路

1.創(chuàng)建字符輸入流BufferedReader對(duì)象

2.創(chuàng)建字符輸出流BufferedWriter對(duì)象

  1. 建StringBuffer對(duì)象sbf,用來臨時(shí)存儲(chǔ)讀取的

    數(shù)據(jù)

  2. 通過循環(huán)實(shí)現(xiàn)文件讀取,并追加到sbf中

  3. 使用replace()方法替換sbf中的內(nèi)容

  4. 將替換后的內(nèi)容寫入到文件中

  5. 關(guān)閉輸入流、輸出流

public class ReaderAndWriterFile {

     public void replaceFile(String file1,String file2) {   
           BufferedReader reader = null;
           BufferedWriter writer = null;
         try {
            //創(chuàng)建 FileReader對(duì)象和FileWriter對(duì)象.
            FileReader fr  = new FileReader(file1);  
            FileWriter fw = new FileWriter(file2);
            //創(chuàng)建 輸入、輸入出流對(duì)象.
            reader = new BufferedReader(fr);
            writer = new BufferedWriter(fw);
            String line = null;
            StringBuffer sbf=new StringBuffer();  
            //循環(huán)讀取并追加字符
            while ((line = reader.readLine()) != null) {
                sbf.append(line);  
            }
            System.out.println("替換前:"+sbf);
            /*替換內(nèi)容*/
            String newString=sbf.toString().replace("{name}", "歐歐");
            newString = newString.replace("{type}", "狗狗");
            newString = newString.replace("{master}", "李偉");
            System.out.println("替換后:"+newString);
            writer.write(newString);  //寫入文件       
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            //關(guān)閉 reader 和 writer.
            try {
                if(reader!=null)
                    reader.close();
                if(writer!=null)
                    writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    public static void main(String[] args) {
        ReaderAndWriterFile obj = new ReaderAndWriterFile();
        obj.replaceFile("c:\\pet.template", "D:\\myDoc\\pet.txt");          
    }
}

使用字符流讀寫文本更合適

使用字節(jié)流讀寫字節(jié)文件(音頻,視頻,圖片,壓縮文件等)更合適,文本文件也可以看成是有字節(jié)組成

圖片拷貝

public class move {  
    public static void main(String[] args)  
    {  
        String src="E:/DesktopFile/Android/CSDN.jpg";  
        String target="E:/DesktopFile/Android/test/CSDN.jpg";  
        copyFile(src,target);  
    }  
    public static void copyFile(String src,String target)  
        {     
            File srcFile = new File(src);    
               File targetFile = new File(target);    
               try {    
                   InputStream in = new FileInputStream(srcFile);     
                   OutputStream out = new FileOutputStream(targetFile);    
                   byte[] bytes = new byte[1024];    
                   int len = -1;    
                   while((len=in.read(bytes))!=-1)  
                   {    
                       out.write(bytes, 0, len);    
                   }    
                   in.close();    
                   out.close();    
               } catch (FileNotFoundException e) {    
                   e.printStackTrace();    
               } catch (IOException e) {    
                   e.printStackTrace();    
               }    
               System.out.println("文件復(fù)制成功");   

        }  

    }  

--------------------------------------------------------------------------

最后一道題

創(chuàng)建一個(gè)txt文件夾email.txt文件
親愛的{to}
{content}
yours{from}

第一個(gè)類

package com.company;

import java.io.*;

/**
 * Created by ttc on 2018/1/15.
 */
public class TemplateReplace {
    public static void main(String[] args) throws IOException {
        //讀取模板內(nèi)容
        FileReader fileReader = new FileReader("e:/email.txt");
        BufferedReader bufferedReader = new BufferedReader(fileReader);

        String strLine = bufferedReader.readLine();

        StringBuilder stringBuilder = new StringBuilder();
        while (strLine != null)
        {
            stringBuilder.append(strLine);
            strLine = bufferedReader.readLine();
        }

//        System.out.println(stringBuilder.toString());

        Email email = new Email();
        email.setTo("寶貝");
        email.setContent("新年快樂");
        email.setFrom("大甜甜");

        String strContent = stringBuilder.toString();//親愛的{to}  {content}       yours {from}
        strContent = strContent.replace("{to}",email.getTo());
        strContent = strContent.replace("{content}",email.getContent());
        strContent = strContent.replace("{from}",email.getFrom());
//        System.out.println(strContent);

        FileWriter fileWriter = new FileWriter("e:/my_email.txt");//文件夾在那個(gè)位置,代碼生成文件
        BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);

        bufferedWriter.write(strContent);
        bufferedWriter.flush();

        fileReader.close();
        bufferedReader.close();
        fileWriter.close();
        bufferedWriter.close();

    }
}

第二個(gè)類

package com.company;

/**
 * Created by ttc on 18-1-15.
 */
public class Email {
    private String to;
    private String content;
    private String from;

    public String getTo() {
        return to;
    }

    public void setTo(String to) {
        this.to = to;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public String getFrom() {
        return from;
    }

    public void setFrom(String from) {
        this.from = from;
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容

  • 什么是文件? 文件可認(rèn)為是相關(guān)記錄或放在一起的數(shù)據(jù)的集合 文件一般存儲(chǔ)在哪里? JAVA程序如何訪問文件屬性? j...
    __豆約翰__閱讀 1,366評(píng)論 0 5
  • 一、流的概念和作用。 流是一種有順序的,有起點(diǎn)和終點(diǎn)的字節(jié)集合,是對(duì)數(shù)據(jù)傳輸?shù)目偝苫虺橄蟆<磾?shù)據(jù)在兩設(shè)備之間的傳輸...
    布魯斯不吐絲閱讀 10,101評(píng)論 2 95
  • 1 IONo18 1.1IO框架 【 IO:Input Output 在程序運(yùn)行的過程中,可能需要對(duì)一些設(shè)備進(jìn)...
    征程_Journey閱讀 978評(píng)論 0 1
  • 眉初和易寒是玩游戲認(rèn)識(shí)的。 一個(gè)低調(diào)玩什么都會(huì)的大神,一個(gè)技術(shù)摳腳卻十分咋呼的菜狗子。本來一個(gè)天上一個(gè)地下,玩著同...
    眉初阿閱讀 511評(píng)論 0 0