[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-cwjw6wr6-1631152193681)(C:\Users\hrqfly\AppData\Roaming\Typora\typora-user-images\image-20210909085400412.png)]
用FileInputStream读取图片文件代码实例:
package moose;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class InputStreamDemo {
public static void main(String[] args) {
FileInputStream fis = null;
try {
//创建字节输入流
fis = new FileInputStream("d:/pic.jpg");
int temp = 0;
while ((temp = fis.read())!=-1){
System.out.println(temp);
}
}catch (Exception e){
e.printStackTrace();
}finally {
try {
if (fis != null) {
fis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
上述代码小改动
FileOutputStream实现文件写入:
package moose;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class InputStreamDemo {
public static void main(String[] args) {
FileInputStream fis = null;
FileOutputStream fos = null;
try {
//创建字节输入流
fis = new FileInputStream("d:/pic.jpg");
//创建字节输出流
fos = new FileOutputStream("d:/pic1.jpg");
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();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
d盘根目录现在如下: