最简单的文件、图片的读写操作

来源:互联网 发布:淘宝客单品推广 编辑:程序博客网 时间:2024/06/05 14:49

`具体的操作还是得对API进行改进“
package com.io;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
import javax.imageio.ImageIO;
public class ReadAndWrite {
public static void main(String[] args) throws Exception{
read();//读文件
write(read());//写文件
readImg();//读图片
writeImg(readImg());
}
/*
* 读取文件
*/
public static String read(){
String str=”“;
try {
FileInputStream in=new FileInputStream(new File(“D://abc.txt”));
if(new File(“D://abc.txt”).exists()){
byte[]b=new byte[1000];
int temp=0;
while ((temp=in.read(b))!=-1) {
//System.out.println((char)temp);
}
str=new String(b);
}
in.close();

    } catch (Exception e) {        // TODO Auto-generated catch block        e.printStackTrace();    }    return str;}/* * 写文件 */public static void write(String str){    try {        FileOutputStream os=new FileOutputStream(new File("D://bcd.txt"));        os.write(str.getBytes());        os.flush();        os.close();    } catch (Exception e) {        // TODO Auto-generated catch block        e.printStackTrace();    }}/* * 读取图片 */public static BufferedImage readImg(){    BufferedImage readImg=null;    try {        String[] formatsArr=ImageIO.getReaderFormatNames();        System.out.println(Arrays.asList(formatsArr));        readImg=ImageIO.read(new File("D://123.png"));    } catch (Exception e) {        // TODO Auto-generated catch block        e.printStackTrace();    }    return readImg;}/* * 写图片 */public static void writeImg(BufferedImage img){    try {        ImageIO.write(img, "png", new File("D://234.png"));    } catch (IOException e) {        // TODO Auto-generated catch block        e.printStackTrace();    }}

}

“`

原创粉丝点击