Wednesday, February 5, 2014

What this code help facie problem ah.


            
public void downloadFile (String URL, String fileName)
throws Exception {
InputStream is = null;
try {
/ / Create, open, connected
URL myUrl = new URL (URL);
URLConnection connection = myUrl.openConnection ();
connection.connect ();

/ / Get access to the content and save it in the input stream.
is = connection.getInputStream ();
/ / Get the total length of the file. Note that there may be due to lack of file size and thrown
int len ​​= connection.getContentLength ();

Log.e ("down", String.valueOf (len));
Log.e ("fileName", fileName);
if (is! = null) {
File file = new File (SD_PATH + fileName);
/ / If the file exists, delete the file.
if (file.exists ()) {
file.delete ();
Log.e ("down", "Deleted Files");
}
RandomAccessFile randomAccessFile = new RandomAccessFile (
SD_PATH + fileName, "rw");
byte [] buffer = new byte [4096];
int length = -1;
while ((length = is.read (buffer))! = -1) {
randomAccessFile.write (buffer, 0, length);
nowSize + = length;
Log.e ("down", "being downloaded...." + (NowSize));
}

is.close ();
randomAccessFile.close ();

}
} Catch (Exception e) {

Log.e ("down", e.toString ());
} Finally {

}

Debug debugging a bit, to RandomAccessFile randomAccessFile = new RandomAccessFile (SD_PATH + fileName, "rw"); time, jump catch, and in the end what is the problem ah. .
Logcat error information, catch the printed java.io.FileNotFoundException: / sdcard/DBMarket/TogicVideo_V2_5_release_togic_ZNDS.apk: open failed: ENOENT (No such file or directory)

Reply:
/ Sdcard / DBMarket / this path exist? Use Java IO will automatically create a file when writing files, but if the path does not exist, then an exception will be reported, the need to manually create this path. Namely:
 
File p = new File (filePath);
if (! p.exists ()) {
p.mkdirs ();
}


In addition, it creates a path back is best not to add /, then create IO stream when using filePath + File.separator + fileName
Reply:
cited a floor books1958 reply:
/ sdcard / DBMarket / this path exist? Use Java IO will automatically create a file when writing files, but if the path does not exist, then an exception will be reported, the need to manually create this path. Namely:
 
File p = new File (filePath);
if (! p.exists ()) {
p.mkdirs ();
}


In addition, it creates a path back is best not to add /, then create IO stream when using filePath + File.separator + fileName

This really is the reason, ah, ah thank you very much! !

No comments:

Post a Comment