4.檔案位元組流
阿新 • • 發佈:2022-04-10
檔案位元組流輸入流 FileInputStream 通過位元組的方式讀取檔案,適合讀取所有型別的檔案(影象,視訊,文字檔案等),java也專門提供了FileReader讀取文字檔案
import java.io.FileInputStream;
public class Dome03 {
public static void main(String[] args) {
FileInputStream fis = null;
try {
fis = new FileInputStream("d:/zm.png");
int temp = 0;
while ((temp = fis.read()) != -1) {
System.out.print(temp);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (fis != null) {
fis.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
2.檔案位元組流-輸出流
檔案位元組流輸出流 FileOutputStream 把讀取到的位元組流寫出到指定位置
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class Dome03 {
public static void main(String[] args) {
FileInputStream fis = null;
FileOutputStream fos = null;
try {
//建立位元組流輸入物件
fis = new FileInputStream("d:/zm.png");
//建立位元組流輸出物件
fos = new FileOutputStream("d:/dome.png");
int temp = 0;
while ((temp = fis.read()) != -1) {
fos.write(temp);//這一步只是把檔案位元組流寫到了記憶體中
}
fos.flush();//這一步才是把檔案位元組流寫到磁碟中
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (fis != null) {
fis.close();
}
if (fos != null) {
fos.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}