Java中的输入、输出流中可以用于文件的读写,拷贝。
由于文件都是由字节组成的,可以将文件中的内容以字节的方式读取出来。
输入流还可以直接转换为图片来使用。其实ImageIcon提供了方法可以直接打开。
读取文件的实例代码如下
public String read_file(String filename){
File f = new File(filename);
try{
java.io.InputStream in = new java.io.FileInputStream(f);
int len = in.available();
byte[] by = new byte[len];
in.read(by);
String msg = new String();
msg = new String(by);
in.close();
return msg;
}catch(Exception e){
e.printStackTrace();
System.out.println("文件读取失败");
}
return null;
}
写入文件的代码如下
public boolean write_file(String filename,String msg){
File f = new File(filename);
try{
java.io.OutputStream out = new java.io.FileOutputStream(f);
byte[] by = msg.getBytes();
out.write(by);
out.flush();
out.close();
return true;
}catch(Exception e){
e.printStackTrace();
System.out.println("文件写入异常");
}
return false;
}
或者读取图片
public BufferedImage getim_file(String filename){
File f = new File(filename);
try{
java.io.InputStream in = new java.io.FileInputStream(f);
BufferedImage img = ImageIO.read(in);
return img;
}catch(Exception e){
e.printStackTrace();
System.out.println("文件读取失败");
return null;
}
}