我正在下载一个 zip 文件夹并保存在我的 Android 设备中的特定文件夹中。我的应用程序在压缩文件夹时未访问该文件夹。我想在从服务器下载后解压缩文件夹并保存在特定文件夹中。
我的代码在这里:
public void DownloadDatabase(String DownloadUrl, String fileName) {
try {
File root = android.os.Environment.getExternalStorageDirectory();
File dir = new File(root.getAbsolutePath() + "/timy/databases");
if(dir.exists() == false){
dir.mkdirs();
}
URL url = new URL("http://myexample.com/android/timy.zip");
File file = new File(dir,fileName);
long startTime = System.currentTimeMillis();
Log.d("DownloadManager" , "download url:" +url);
Log.d("DownloadManager" , "download file name:" + fileName);
URLConnection uconn = url.openConnection();
uconn.setConnectTimeout(TIMEOUT_SOCKET);
InputStream is = uconn.getInputStream();
ZipInputStream zipinstream = new ZipInputStream(new BufferedInputStream(is));
ZipEntry zipEntry;
while((zipEntry = zipinstream.getNextEntry()) != null){
String zipEntryName = zipEntry.getName();
File file1 = new File(file + zipEntryName);
if(file1.exists()){
}else{
if(zipEntry.isDirectory()){
file1.mkdirs();
}
}
}
BufferedInputStream bufferinstream = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(5000);
int current = 0;
while((current = bufferinstream.read()) != -1){
baf.append((byte) current);
}
FileOutputStream fos = new FileOutputStream( file);
fos.write(baf.toByteArray());
fos.flush();
fos.close();
Log.d("DownloadManager" , "download ready in" + ((System.currentTimeMillis() - startTime)/1000) + "sec");
}
catch(IOException e) {
Log.d("DownloadManager" , "Error:" + e);
e.printStackTrace();
}
}
我的 logcat 显示错误。只是文件夹正在我的设备中创建,没有文件正在下载解压缩。如果不使用 inputZipStream 方法,那么我的压缩文件夹正在下载并保存在 sdcard 中。当我想解压缩它时,它没有发生。
最佳答案
这篇文章是关于如何使用内置的 Java API 编写一个实用程序类来提取压缩 zip 存档中的文件和目录。
java.util.zip 包提供了以下用于从 ZIP 存档中提取文件和目录的类:
ZipInputStream:这是主要类,可用于读取 zip 文件以及提取存档中的文件和目录(条目)。下面是这个类的一些重要用法: - 通过其构造函数 ZipInputStream(FileInputStream) 读取 zip - 通过方法 getNextEntry() 读取文件和目录的条目 - 通过 read(byte) 方法读取当前条目的二进制数据 - 通过方法 closeEntry() 关闭当前条目 - 通过方法 close() 关闭 zip 文件
ZipEntry:此类表示 zip 文件中的条目。每个文件或目录都表示为一个 ZipEntry 对象。它的方法 getName() 返回一个表示文件/目录路径的字符串。该路径采用以下形式: folder_1/subfolder_1/subfolder_2/…/subfolder_n/file.ext
基于 ZipEntry 的路径,我们在解压缩 zip 文件时重新创建目录结构。
下面的类用于解压缩下载 zip 和提取文件并存储您想要的位置。
public class UnzipUtil
{
private String zipFile;
private String location;
public UnzipUtil(String zipFile, String location)
{
this.zipFile = zipFile;
this.location = location;
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());
byte[] buffer = new byte[8192];
int len;
while ((len = zin.read(buffer)) != -1)
{
fout.write(buffer, 0, len);
}
fout.close();
zin.closeEntry();
}
}
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();
}
}
}
MainActivity.Class:
public class MainActivity extends Activity
{
private ProgressDialog mProgressDialog;
String Url="http://hasmukh/hb.zip";
String unzipLocation = Environment.getExternalStorageDirectory() + "/unzipFolder/";
String StorezipFileLocation =Environment.getExternalStorageDirectory() + "/DownloadedZip";
String DirectoryName=Environment.getExternalStorageDirectory() + "/unzipFolder/files/";
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
DownloadZipfile mew = new DownloadZipfile();
mew.execute(url);
}
//-This is method is used for Download Zip file from server and store in Desire location.
class DownloadZipfile extends AsyncTask<String, String, String>
{
String result ="";
@Override
protected void onPreExecute()
{
super.onPreExecute();
mProgressDialog = new ProgressDialog(MainActivity.this);
mProgressDialog.setMessage("Downloading...");
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
}
@Override
protected String doInBackground(String... aurl)
{
int count;
try
{
URL url = new URL(aurl[0]);
URLConnection conexion = url.openConnection();
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(StorezipFileLocation);
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.close();
input.close();
result = "true";
} catch (Exception e) {
result = "false";
}
return null;
}
protected void onProgressUpdate(String... progress)
{
Log.d("ANDRO_ASYNC",progress[0]);
mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}
@Override
protected void onPostExecute(String unused)
{
mProgressDialog.dismiss();
if(result.equalsIgnoreCase("true"))
{
try
{
unzip();
} catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
{
}
}
}
//This is the method for unzip file which is store your location. And unzip folder will store as per your desire location.
public void unzip() throws IOException
{
mProgressDialog = new ProgressDialog(MainActivity.this);
mProgressDialog.setMessage("Please Wait...");
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
new UnZipTask().execute(StorezipFileLocation, DirectoryName);
}
private class UnZipTask extends AsyncTask<String, Void, Boolean>
{
@SuppressWarnings("rawtypes")
@Override
protected Boolean doInBackground(String... params)
{
String filePath = params[0];
String destinationPath = params[1];
File archive = new File(filePath);
try
{
ZipFile zipfile = new ZipFile(archive);
for (Enumeration e = zipfile.entries(); e.hasMoreElements();)
{
ZipEntry entry = (ZipEntry) e.nextElement();
unzipEntry(zipfile, entry, destinationPath);
}
UnzipUtil d = new UnzipUtil(StorezipFileLocation, DirectoryName);
d.unzip();
}
catch (Exception e)
{
return false;
}
return true;
}
@Override
protected void onPostExecute(Boolean result)
{
mProgressDialog.dismiss();
}
private void unzipEntry(ZipFile zipfile, ZipEntry entry,String outputDir) throws IOException
{
if (entry.isDirectory())
{
createDir(new File(outputDir, entry.getName()));
return;
}
File outputFile = new File(outputDir, entry.getName());
if (!outputFile.getParentFile().exists())
{
createDir(outputFile.getParentFile());
}
// Log.v("", "Extracting: " + entry);
BufferedInputStream inputStream = new BufferedInputStream(zipfile.getInputStream(entry));
BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile));
try
{
}
finally
{
outputStream.flush();
outputStream.close();
inputStream.close();
}
}
private void createDir(File dir)
{
if (dir.exists())
{
return;
}
if (!dir.mkdirs())
{
throw new RuntimeException("Can not create dir " + dir);
}
}}
}
Note: Do not forgot to add below permission in android Manifest.xml file.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" ></uses-permission>
<uses-permission android:name="android.permission.INTERNET" />
关于java - 在 Android 中以编程方式解压缩文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16142311/
我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看rubyzip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d
我试图在一个项目中使用rake,如果我把所有东西都放到Rakefile中,它会很大并且很难读取/找到东西,所以我试着将每个命名空间放在lib/rake中它自己的文件中,我添加了这个到我的rake文件的顶部:Dir['#{File.dirname(__FILE__)}/lib/rake/*.rake'].map{|f|requiref}它加载文件没问题,但没有任务。我现在只有一个.rake文件作为测试,名为“servers.rake”,它看起来像这样:namespace:serverdotask:testdoputs"test"endend所以当我运行rakeserver:testid时
我的目标是转换表单输入,例如“100兆字节”或“1GB”,并将其转换为我可以存储在数据库中的文件大小(以千字节为单位)。目前,我有这个:defquota_convert@regex=/([0-9]+)(.*)s/@sizes=%w{kilobytemegabytegigabyte}m=self.quota.match(@regex)if@sizes.include?m[2]eval("self.quota=#{m[1]}.#{m[2]}")endend这有效,但前提是输入是倍数(“gigabytes”,而不是“gigabyte”)并且由于使用了eval看起来疯狂不安全。所以,功能正常,
Rails2.3可以选择随时使用RouteSet#add_configuration_file添加更多路由。是否可以在Rails3项目中做同样的事情? 最佳答案 在config/application.rb中:config.paths.config.routes在Rails3.2(也可能是Rails3.1)中,使用:config.paths["config/routes"] 关于ruby-on-rails-Rails3中的多个路由文件,我们在StackOverflow上找到一个类似的问题
对于具有离线功能的智能手机应用程序,我正在为Xml文件创建单向文本同步。我希望我的服务器将增量/差异(例如GNU差异补丁)发送到目标设备。这是计划:Time=0Server:hasversion_1ofXmlfile(~800kiB)Client:hasversion_1ofXmlfile(~800kiB)Time=1Server:hasversion_1andversion_2ofXmlfile(each~800kiB)computesdeltaoftheseversions(=patch)(~10kiB)sendspatchtoClient(~10kiBtransferred)Cl
我正在寻找执行以下操作的正确语法(在Perl、Shell或Ruby中):#variabletoaccessthedatalinesappendedasafileEND_OF_SCRIPT_MARKERrawdatastartshereanditcontinues. 最佳答案 Perl用__DATA__做这个:#!/usr/bin/perlusestrict;usewarnings;while(){print;}__DATA__Texttoprintgoeshere 关于ruby-如何将脚
我试图获取一个长度在1到10之间的字符串,并输出将字符串分解为大小为1、2或3的连续子字符串的所有可能方式。例如:输入:123456将整数分割成单个字符,然后继续查找组合。该代码将返回以下所有数组。[1,2,3,4,5,6][12,3,4,5,6][1,23,4,5,6][1,2,34,5,6][1,2,3,45,6][1,2,3,4,56][12,34,5,6][12,3,45,6][12,3,4,56][1,23,45,6][1,2,34,56][1,23,4,56][12,34,56][123,4,5,6][1,234,5,6][1,2,345,6][1,2,3,456][123
我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i
使用带有Rails插件的vim,您可以创建一个迁移文件,然后一次性打开该文件吗?textmate也可以这样吗? 最佳答案 你可以使用rails.vim然后做类似的事情::Rgeneratemigratonadd_foo_to_bar插件将打开迁移生成的文件,这正是您想要的。我不能代表textmate。 关于ruby-使用VimRails,您可以创建一个新的迁移文件并一次性打开它吗?,我们在StackOverflow上找到一个类似的问题: https://sta
好的,所以我的目标是轻松地将一些数据保存到磁盘以备后用。您如何简单地写入然后读取一个对象?所以如果我有一个简单的类classCattr_accessor:a,:bdefinitialize(a,b)@a,@b=a,bendend所以如果我从中非常快地制作一个objobj=C.new("foo","bar")#justgaveitsomerandomvalues然后我可以把它变成一个kindaidstring=obj.to_s#whichreturns""我终于可以将此字符串打印到文件或其他内容中。我的问题是,我该如何再次将这个id变回一个对象?我知道我可以自己挑选信息并制作一个接受该信