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();
}
}
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:不可以,字符流讀到的數據,如果在碼表裡找不到對應的數,則返回一個未知字符對應的數字,未知字符占一個字節。同理,字節流如果錯誤地截斷字符,也會導致亂碼。