1. 程式人生 > 其它 >JAVA初學——week14 檔案複製

JAVA初學——week14 檔案複製

技術標籤:JAVA_homework

使用Scanner & PrintWriter讀寫文字

package text1;

import java.io.FileNotFoundException;
import java.util.Scanner;

public class Scanner_PrintWriter {
    public static void main(String[] args) throws FileNotFoundException {
        //建立一個"input.txt的檔案"
        java.io.File file =
new java.io.File("src/text1/input.txt"); java.io.File file1 = new java.io.File("src/text1/output.txt"); //給"input.txt"輸入內容 try(java.io.PrintWriter output = new java.io.PrintWriter(file)){ output.println("Hello World!"); output.
print("114514"); } Scanner input = new Scanner(file); try (java.io.PrintWriter output1 = new java.io.PrintWriter(file1);){ while(input.hasNext()){ String x = input.nextLine(); output1.println(x); System.out.
println(x); } } input.close(); } }

讀寫結果:在這裡插入圖片描述

InputStream 和 OutputStream讀寫檔案

package text2;
import java.io.*;
public class InputStream_OutputStream {
    public static void main(String[] args) throws Exception {
        InputStream fis = new FileInputStream("src/text2/input.txt");
        OutputStream fis1 = new FileOutputStream("src/text2/output.txt");
        int i;
        while((i = fis.read()) != -1){
            System.out.print((char)i);
            fis1.write(i);
        }
    }
}

讀寫結果:
在這裡插入圖片描述