2016-02-18 115 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