我正在尝试编写类来从服务器下载文件并将其存储在SD卡上。但是我得到一个例外java.io.FileNotFoundException:/mnt/sdcard/files.zip(没有这样的文件或目录)。
我的主要课程是
public class DownloadZipActivity extends Activity {
/** Called when the activity is first created. */
int count;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
URL url = new URL(
"url to download");
/* URLConnection conexion = url.openConnection();
conexion.connect();
*/
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setDoInput(true);
conn.setConnectTimeout(1000); // timeout 10 secs
conn.connect();
int lenghtOfFile = conn.getContentLength();
Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream("/mnt/sdcard/external_sd/files.zip");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishProgress(""+(int)((total*100)/lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String zipFile = Environment.getExternalStorageDirectory() + "/files.zip";
String unzipLocation = Environment.getExternalStorageDirectory() + "/unzipped/";
Decompress d = new Decompress(zipFile, unzipLocation);
d.unzip();
}
}
和解压缩类是
public class Decompress {
String _zipFile;
String _location;
public Decompress(String zipFile, String unzipLocation) {
// TODO Auto-generated constructor stub
_zipFile = zipFile;
_location = unzipLocation;
_dirChecker("");
}
public void unzip() {
try {
FileInputStream fin = new FileInputStream(_zipFile);
ZipInputStream zin = new ZipInputStream(fin);
ZipEntry ze = null;
while ((ze = zin.getNextEntry()) != null) {
Log.v("Decompress", "Unzipping " + ze.getName());
if(ze.isDirectory()) {
_dirChecker(ze.getName());
} else {
FileOutputStream fout = new FileOutputStream(_location + ze.getName());
for (int c = zin.read(); c != -1; c = zin.read()) {
fout.write(c);
}
zin.closeEntry();
fout.close();
}
}
zin.close();
} catch(Exception e) {
Log.e("Decompress", "unzip", e);
}
}
private void _dirChecker(String dir) {
File f = new File(_location + dir);
if(!f.isDirectory()) {
f.mkdirs();
}
}
}
答案 0 :(得分:0)
仔细查看您的代码
下载并保存文件时,您将其保存在以下路径中
OutputStream output = new FileOutputStream("/mnt/sdcard/external_sd/files.zip");
但在阅读时你指的是以下路径
String zipFile = Environment.getExternalStorageDirectory() + "/files.zip";
相当于
String zipFile = "/mnt/sdcard/files.zip";
你应该写
String zipFile = Environment.getExternalStorageDirectory() + "/external_sd/files.zip";
希望这有帮助