畢向東_Java根底視頻教程第19天_IO流(11~12)。本站提示廣大學習愛好者:(畢向東_Java根底視頻教程第19天_IO流(11~12))文章只能為提供參考,不一定能成為您想要的結果。以下是畢向東_Java根底視頻教程第19天_IO流(11~12)正文
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
/*
字符流
Reader/Writer
FileReader/FileWriter
BufferedReader/BufferedWriter
字節流:
InputStream/OutputStream
FileInputStream/FileOutputStream
需求:想要操作圖片數據,這時就要用到字節流
*/
public class FileStream {
public static void main(String[] args) throws IOException {
// writeFile();
readFile_2();
}
public static void writeFile() throws IOException {
FileOutputStream fos = new FileOutputStream("fos.txt");
fos.write("abc凶猛".getBytes());
// 寫需求close無需flush -- 字符流底層也是一個字節一個字節停止操作,但是需求讀取若干個字節,然後查碼表輸入字符,所以觸及緩存和flush.而字節流就不需求緩存也就無需flush
fos.close();
}
public static void readFile_0() throws IOException {
FileInputStream fis = new FileInputStream("fos.txt");
// 一個字節一個字節讀
int ch;
while ((ch = fis.read()) != -1) {
System.out.println((char) ch);
}
fis.close();
}
public static void readFile_1() throws IOException {
FileInputStream fis = new FileInputStream("fos.txt");
byte[] buf = new byte[1024];// 1024*N 是字節數組適宜的大小
int len;
while ((len = fis.read(buf)) != -1) {
System.out.println(new String(buf, 0, len, "utf-8"));
System.out.println(new String(buf, 0, len));
}
fis.close();
}
// 字節流特有的available()辦法
public static void readFile_2() throws IOException {
FileInputStream fis = new FileInputStream("fos.txt");
// int available() 前往下一次對此輸出流調用的辦法"可以不受阻塞地從'此輸出流'讀取(或跳過)的估量剩余字節數"(含換行符)
// 假如new一個容量大小恰恰為剩余文件字節數的byte[fis.available()],就無需循環而一次讀完.但文件體積很大的狀況下byte[]請求內存會失敗
byte[] buf = new byte[fis.available()];
fis.read(buf);
System.out.println(new String(buf));
fis.close();
}
}
第19天-12-IO流(拷貝圖片)
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
/*
拷貝一個圖片,思緒:
1.用字節讀取流對象和源圖片關聯
2.用字節寫入流對象創立一個圖片文件,用於存儲獲取到的圖片數據.
3.經過循環讀寫,完成數據的存儲
4.封閉資源
*/
public class CopyPic {
public static void main(String[] args) {
FileOutputStream fos = null;
FileInputStream fis = null;
try {
fos = new FileOutputStream("2.png");
fis = new FileInputStream("1.png");
byte[] buf = new byte[1024];
int len;
while ((len = fis.read(buf)) != -1) {
fos.write(buf, 0, len);
}
} catch (Exception e) {
throw new RuntimeException("復制文件失敗");
} finally {
try {
if (fis != null) fis.close();
} catch (IOException e) {
throw new RuntimeException("讀取流封閉失敗");
}
try {
if (fos != null) fos.close();
} catch (IOException e) {
throw new RuntimeException("輸入流封閉失敗");
}
}
}
}
Q:字符流可以用於圖片復制嗎?
A:不可以,字符流讀到的數據,假如在碼表裡找不到對應的數,則前往一個未知字符對應的數字,未知字符占一個字節。同理,字節流假如錯誤地截斷字符,也會招致亂碼。