I have java code which purpose is download video files in small part (e.g. equal size of two part) using http request and later need to merge the files in the same condition so that I get back the original file. But I am getting the corrupted files while merging. In addition to it, the merge file size has increased than original.
File reading:
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;
}
Merging:
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();
}