[英]File Corrupted while downloading and during merging
我有Java代碼,目的是使用http請求以一小部分(例如,兩部分相等的大小)下載視頻文件,以后需要在相同條件下合並文件,這樣我才能取回原始文件。 但是我在合並時收到損壞的文件。除了它,合並文件的大小比原始文件增加了。
我使用的代碼如下:
對於文件讀取:
public static int ReadFiles(String address,int StartPos,
int LastPos,String filename) throws IOException
{
// Create the byte array to hold the data
byte[] bytes = new byte[(int)LastPos];
try {
url = new URL(address);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Opening connection to " + address + "...");
System.out.println("Start Address " + StartPos + " End Postion "+LastPos);
URLConnection urlC = null;
try {
urlC = url.openConnection();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
urlC.setRequestProperty("User-Agent","");
urlC.connect();
InputStream is = urlC.getInputStream();
FileOutputStream fos = null;
fos = new FileOutputStream(filename);
int oneChar,CharRead;
System.out.println("Downloading bytes: ");
is.skip(StartPos);
while (((oneChar = is.read()) != -1) ) {
// System.out.print((char)oneChar);
fos.write(oneChar);
StartPos++;
System.out.print("\r"+StartPos);
if((StartPos>=LastPos))
{
System.out.println("Downloading break at : "+StartPos+"="+LastPos);
break;
}
// if(count==25260)break;
}
is.close();
fos.close();
//System.out.println(StartPos+ " byte(s) copied");
System.out.println("File Downloader Completed Work!");
return 0;
}
對於合並:
public static void mergeFiles(File[] files, File mergedFile) {
FileWriter fstream = null;
BufferedWriter out = null;
try {
fstream = new FileWriter(mergedFile, true);
out = new BufferedWriter(fstream);
} catch (IOException e1) {
e1.printStackTrace();
}
for (File f : files) {
System.out.println("merging: " + f.getName());
FileInputStream fis;
try {
fis = new FileInputStream(f);
BufferedReader in = new BufferedReader(new InputStreamReader(fis));
String aLine;
while ((aLine = in.readLine()) != null) {
out.write(aLine);
out.newLine();
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
對於部分下載,可以使用Range請求屬性(如果服務器支持HTTP 1.1): Java:resume在URLConnection中下載
合並期間請不要使用Reader,因為它適用於字符而非字節。 您可以改為使用以下函數:
public static void copyStream(InputStream is, OutputStream os) throws IOException {
byte[] buffer = new byte[10000];
while (true) {
int len = is.read(buffer);
if (len < 0)
break;
if (len > 0)
os.write(buffer, 0, len);
}
}
因此,for循環將類似於:
for (File f : files) {
System.out.println("merging: " + f.getName());
FileInputStream fis = null;
try {
fis = new FileInputStream(f);
copyStream(fis, out);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis != null)
fis.close();
}
}
PS:還有一些流復制操作的標准實現。 例如: http : //commons.apache.org/proper/commons-io/javadocs/api-2.4/org/apache/commons/io/IOUtils.html#copy(java.io.InputStream,%20java.io。 OutputStream中)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.