//代码://测试类:public class Test {
 public static void main(String[] args) {
  Image img = new Image();
  String str = img.getRimg();
  img.getWimg(str);
 }
} //输入、输出类import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;public class Image {
 public String getRimg(){
  String s = "";
  int i;
  try {
   FileReader in = new FileReader("text\\img.txt");
    while((i=in.read())!=-1){
     s = s+(char)i;
    }
    in.close();
  }catch (FileNotFoundException e) {
   e.printStackTrace();
  }catch (IOException e) {
   e.printStackTrace();
  }finally{
   return s;
  }
 } //输出类
 public void getWimg(String content){
  try {
   FileWriter out = new FileWriter("text\\img.jpg");
   char[] ch = content.toCharArray();
   System.out.println(ch);
   for(int i=0;i<ch.length;i++){
    out.write(ch[i]);
   }
   out.close();
  } catch (IOException e) {
   e.printStackTrace();
  }
 }
}请教大家为什么我运行出来的图片,没有预览啊,是空白的!代码那里有错吗?

解决方案 »

  1.   

    如果你是在gui下想显示图片  有专门的api
    在jsp中通过读取流在servlet可以显示图片!!
    需要把servlet 设置为 text/image (可能是)
    长时间没动web了 
      

  2.   

    1、图片应该用字节流,不能用字符流。
    2、建议用BufferedOutputStream、BufferedInputStream提高速度
    3、大量String i;
    i+= somestring;建议使用StringBuilder、StringBuffer,不然跑N久都不出结果import java.io.*;public class Test {
     public static void main(String[] args) {
      Image img = new Image();
      String str = img.getRimg();
      img.getWimg(str);
     }
    } //输入、输出类class Image {
     public String getRimg(){
      
      StringBuilder builder = new StringBuilder(1000000);
      int i;
      try {
       new File("text\\img.txt").createNewFile();
       FileInputStream in = new FileInputStream("text\\img.txt");
       BufferedInputStream bis = new BufferedInputStream(in);
        while((i=in.read())!=-1){
         builder.append((char)i);
        }
        bis.close();
      }catch (FileNotFoundException e) {
       e.printStackTrace();
      }catch (IOException e) {
       e.printStackTrace();
      }finally{
       return builder.toString();
      }
     } //输出类
     public void getWimg(String content){
      try {
       new File("text\\img.txt").createNewFile();
       FileOutputStream out = new FileOutputStream("text\\img.jpg");
       BufferedOutputStream bos = new BufferedOutputStream(out);
       char[] ch = content.toCharArray();
       System.out.println(ch);
       for(int i=0;i<ch.length;i++){
        bos.write(ch[i]);
       }
       bos.flush();
       bos.close();
      } catch (IOException e) {
       e.printStackTrace();
      }
     }
    }