[Java] java分别通过字节流、字符流、二进制读取文件 →→→→→进入此内容的聊天室

来自 , 2021-03-03, 写在 Java, 查看 106 次.
URL http://www.code666.cn/view/b8c4c8b2
  1. import java.io.*;
  2. import javax.swing.*;
  3. public class Start
  4. {
  5.         public static void main(String args[]) throws Exception{
  6.                
  7.                 //源文件,必须存在,路径可选
  8.                 File sf = new File("H:/javapro/files/source.jpg");     
  9.                
  10.                 //目的文件,因为要向其中写入,指定文件可以不存在,由程序生成
  11.                 File df = new File("H:/javapro/files/dest.jpg");
  12.                 new ReadWriteGra(sf,df);
  13.                 new UseGra(df);
  14.         }
  15. }
  16.  
  17. class ReadWriteGra
  18. {
  19.         FileInputStream in = null;
  20.         FileOutputStream out = null;
  21.         public ReadWriteGra(File sourceFile,File destFile) throws Exception{
  22.                 byte[] buf = new byte[1024];
  23.                 int len = 0;
  24.                 in = new FileInputStream(sourceFile);
  25.                 out = new FileOutputStream(destFile,true);
  26.                 while( (len = in.read(buf)) != -1 ){
  27.                         out.write(buf,0,len);
  28.                 }
  29.                 out.close();
  30.         }
  31. }
  32. class UseGra extends JFrame
  33. {
  34.         public UseGra(File picFile) throws Exception{
  35.  
  36.                 this.setVisible(true);
  37.                 this.setResizable(false);
  38.                 this.setLayout(null);
  39.                 this.setBounds(600, 200, 400, 370);
  40.                 this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
  41.                 JPanel p1 = (JPanel)this.getContentPane();
  42.                 p1.setOpaque(false);
  43.                 p1.setLayout(null);
  44.                 InputStream is = new FileInputStream(picFile);
  45.                 ByteArrayOutputStream baos = new ByteArrayOutputStream();
  46.                 int b = 0;
  47.                 while((b = is.read())!=-1){
  48.                         baos.write(b);
  49.                 }
  50.                 ImageIcon image = new ImageIcon(baos.toByteArray());
  51.                 JLabel background = new JLabel(image);
  52.                 this.getLayeredPane().add(background, new Integer(Integer.MIN_VALUE));
  53.                 background.setBounds(0, 0, image.getIconWidth(), image.getIconHeight());
  54.                 JButton bt = new JButton("Test_Button");
  55.                 p1.add(bt);
  56.                 bt.setBounds(10,10,150,25);
  57.                 validate();
  58.         }
  59. }
  60. //java/6507

回复 " java分别通过字节流、字符流、二进制读取文件"

这儿你可以回复上面这条便签

captcha