[英]Output file is getting large size than input (original) file
我正在讀取文件並寫入相同的文件,但是問題是下載的文件比輸入的原始文件大2kb。
一段代碼
@Override
public void run() {
try {
BufferedInputStream bis;
ArrayList<byte[]> al =new ArrayList<byte[]>();
File file = new File(Environment.getExternalStorageDirectory(), "test.mp3");
byte[] bytes = new byte[2048];
bis = new BufferedInputStream(new FileInputStream(file));
OutputStream os = socket.getOutputStream();
int read ;
int fileSize = (int) file.length();
int readlen=1024;
while (fileSize>0) {
if(fileSize<1024){
readlen=fileSize;
System.out.println("Hello.........");
}
bytes=new byte[readlen];
read = bis.read(bytes, 0, readlen);
fileSize-=read;
al.add(bytes);
}
ObjectOutputStream out1 = new ObjectOutputStream(new FileOutputStream(Environment.getExternalStorageDirectory()+"/newfile.mp3"));
for(int ii=1;ii<al.size();ii++){
out1.write(al.get(ii));
// out1.flush();
}
out1.close();
File file1 = new File(Environment.getExternalStorageDirectory(), "newfile.mp3");
不要使用ObjectOutputStream
。 只需使用FileOutputStream
或包裝在其周圍的BufferedOutputStream
FileOutputStream
。
在Java中復制流的正確方法如下:
byte[] buffer = new byte[8192]; // or more, or even less, anything > 0 int count; while ((count = in.read(buffer)) > 0) { out.write(buffer, 0, count); } out.close();
請注意,您不需要輸入大小的緩沖區,也不需要在寫入任何輸出之前讀取整個輸入。
希望我每次發布時都能得到$ 1。
我認為您應該使用ByteArrayOutputStream而不是ObjectOutputStream。 我相信這不是原始代碼,而是代碼的各個部分,放置在不同的過程中,否則毫無意義。 例如,如果要從文件中流式傳輸一些數據,請處理該數據,然后將數據寫入另一個文件。
BufferedInputStream bis = null;
ByteArrayOutputStream al = new ByteArrayOutputStream();
FileOutputStream out1 = null;
byte[] bytes;
try {
File file = new File("testfrom.mp3");
bis = new BufferedInputStream(new FileInputStream(file));
int fileSize = (int) file.length();
int readLen = 1024;
bytes = new byte[readLen];
while (fileSize > 0) {
if (fileSize < readLen) {
readLen = fileSize;
}
bis.read(bytes, 0, readLen);
al.write(bytes, 0, readLen);
fileSize -= readLen;
}
bis.close();
} catch (IOException e){
e.printStackTrace();
}
//proceed the data from al here
//...
//finish to proceed
try {
out1 = new FileOutputStream("testto.mp3");
al.writeTo(out1);
out1.close();
} catch (IOException e){
e.printStackTrace();
}
不要忘記在需要的地方使用try-catch
指令
http://codeinventions.blogspot.ru/2014/08/creating-file-from-bytearrayoutputstrea.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.