Java23-IO流拷貝文件到指定路徑


一、主要知識點:

1. FileInputStream   FileOutputStream

2. BufferedInputStream   BufferedOutputStream

3.數據流分類:

流序列中的數據既可以是未經加工的原始二進制數據,也可以是經一定編碼處理后符合某種格式規定的特定數據。因此Java中的流分為兩種:
 1)  字節流:數據流中最小的數據單元是字節
 2)  字符流:數據流中最小的數據單元是字符, Java中的字符是Unicode編碼,一個字符占用兩個字節。
4. IO體系

 

 

二、IO流拷貝文件到指定路徑  測試代碼:

package doudou;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Scanner;

public class test_file_demo1 {
    public static void main(String[] args) throws IOException {
        // 目的:控制台輸入一個文件路徑,拷貝該文件到指定路徑
        // 思路:1.確定輸入的是文件路徑 而不是文件夾路徑或者空 2.是文件的話,創建緩存輸入輸出流 3.讀取文件並寫入輸出流
        Scanner sc = new Scanner(System.in);
        String path = sc.nextLine();
        String tarpath ="D:\\123\\a"  ;
        File file1 =new File(tarpath);
        if(!file1.exists()) {
            System.out.println("目標地址tarpath不存在");
            if(!file1.getParentFile().exists()) {
                file1.getParentFile().mkdir();
            }
            file1.createNewFile();     
        }
        
        if (path.isEmpty()) {
            System.out.println("請輸入文件路徑,如C:\\Users\\183\\Desktop\\2020-演講稿.docx");
        } else {
            File file = new File(path);
            if (file.isFile()) {
                System.out.println("輸入的是文件");

                BufferedInputStream bis = new BufferedInputStream(new FileInputStream(path));
                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(tarpath));
                int b;
                while ((b = bis.read()) != -1) {
                    bos.write(b);
                }
                bis.close();
                bos.close();

            } else if (file.isDirectory()) {
                System.out.println("輸入的是文件夾路徑,請重新輸入 文件路徑");
            }
        }
    }

}

 

 

 圖片來源:https://blog.csdn.net/hguisu/article/details/7418161   侵權刪


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM