2016-02-18 48 views
0

这是我的测试程序。我需要它适用于某个地方。这可能很小,对此抱歉。但我仍然是首发。所以请帮助我。在java中使用InputStream和OutputStream传输时不显示图像

try{ 
     File file1 = new File("c:\\Users\\prasad\\Desktop\\bugatti.jpg"); 
     File file2 = new File("c:\\Users\\prasad\\Desktop\\hello.jpg"); 
     file2.createNewFile(); 
     BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file1))); 
     String data = null; 
     StringBuilder imageBuild = new StringBuilder(); 
     while((data = reader.readLine())!=null){ 
      imageBuild.append(data); 
     } 
     reader.close(); 
     BufferedWriter writer = new BufferedWriter(new PrintWriter(new FileOutputStream(file2))); 
     writer.write(imageBuild.toString()); 
     writer.close(); 
    }catch(IOException e){ 
     e.printStackTrace(); 
    } 

这是文件1 enter image description here

,这是文件2 enter image description here

+2

嗯,你为什么要做'data = reader.readLine()'?用'jpg'文件..?我很肯定你需要使用这个'byte []'这个 – 3kings

+1

你需要在这里使用BufferedImage和ImageIO来满足你的需求。请检查此链接:https://www.dyclassroom.com/image-processing-project/how-to-read-and-write-image-file-in-java –

+1

Javadocs的第一行指出“从文本中读取文本一个字符输入流,' –

回答

1

你可以做以下两种:如果你想使用流

private static void copyFile(File source, File dest) throws IOException { 
Files.copy(source.toPath(), dest.toPath()); 
} 

或者也许这:

private static void copyFile(File source, File dest) 
throws IOException { 
InputStream input = null; 
OutputStream output = null; 
try { 
    input = new FileInputStream(source); 
    output = new FileOutputStream(dest); 
    byte[] buf = new byte[1024]; 
    int bytesRead; 
    while ((bytesRead = input.read(buf)) > 0) { 
     output.write(buf, 0, bytesRead); 
    } 
} finally { 
    input.close(); 
    output.close(); 
} 
} 
+0

感谢兄弟。它的工作。但我不明白的是为什么你采取字节数组大小1024? – Krishna

+1

@Krishna它可以是任何大小,但通常是人们通常做的。 1MB一次。你可以更大但没有理由 – 3kings

+0

是的。谢谢。现在我需要将这个网络字节流发送到另一台电脑。我怎么发送?我是否需要将其转换为字符串并使用http发送参数?其实这就是我带BufferedReader的原因。 – Krishna

1

图像不包含行甚至字符。因此,您不应使用readLine()或者ReadersWriters.您应该直接使用输入和输出流重写复制循环。

+0

谢谢@EJP。现在实际上我想在网络上发送图像。 – Krishna

+0

谢谢@EJP。现在实际上我想在网络上发送图像。那么我应该多次发送循环调用主机的字节吗?这是不可能与缓冲区? – Krishna

+0

@Krishna我不明白你在问什么。请定义'多次调用主机',并说明它与标准复制循环中发生的不同之处。 – EJP

相关问题