共計 1141 個字符,預計需要花費 3 分鐘才能閱讀完成。
要讀取文件并輸出文件流,可以使用 Java 的 FileInputStream 和 FileOutputStream 類。
首先,你需要創建一個 FileInputStream 對象來讀取文件。可以使用該類的構造函數傳入要讀取的文件的路徑作為參數。然后,你可以使用 FileInputStream 對象的 read() 方法來讀取文件的內容,并將其存儲在一個字節數組中。
接下來,你需要創建一個 FileOutputStream 對象來將文件流輸出到指定的位置。可以使用該類的構造函數傳入要輸出的文件的路徑作為參數。然后,你可以使用 FileOutputStream 對象的 write() 方法將之前讀取的字節數組寫入到文件中。
下面是一個簡單的示例代碼:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileReadWriteExample {public static void main(String[] args) {FileInputStream fis = null;
FileOutputStream fos = null;
try {// 創建 FileInputStream 對象來讀取文件
fis = new FileInputStream("input.txt");
// 創建 FileOutputStream 對象來輸出文件流
fos = new FileOutputStream("output.txt");
// 創建一個字節數組來存儲文件內容
byte[] buffer = new byte[1024];
int bytesRead;
// 讀取文件內容并輸出文件流
while ((bytesRead = fis.read(buffer)) != -1) {fos.write(buffer, 0, bytesRead);
}
System.out.println(" 文件讀取并輸出成功!");
} catch (IOException e) {e.printStackTrace();
} finally {// 關閉文件流
try {if (fis != null) {fis.close();
}
if (fos != null) {fos.close();
}
} catch (IOException e) {e.printStackTrace();
}
}
}
}
在上面的示例代碼中,我們使用了 try-catch-finally 塊來處理文件流的打開、讀寫以及關閉。在 finally 塊中,我們關閉了文件流,以確保資源的正確釋放。
請注意,上面的示例代碼中使用的文件路徑是相對路徑(相對于當前的工作目錄)。如果你希望使用絕對路徑或其他路徑,請相應地修改文件路徑。
丸趣 TV 網 – 提供最優質的資源集合!
正文完
發表至: Java
2023-12-13