如何存在与否,如果没有建立在SD卡中的异步任务的新文件,检查文件 [英] How to check file exist or not and if not create a new file in sdcard in async task
问题描述
我想从服务器上下载PDF格式,并存储在SD卡。我尝试类似以下code,但它不会在其他情况下,因为我不是创建了一个文件仍然会给予味精作为文件存在。为什么会这样?
字符串PDF格式;
字符串filenameWithExtension =;
保护无效的onCreate(包savedInstanceState){
意向意图= getIntent();
PDF = intent.getStringExtra(pdfurl);
字符串PATH2 = Environment.getExternalStorageDirectory()+/图片;
Log.v(log_tag初始路径,路径:+ PATH2);
档案文件2 =新的文件(PATH2);
如果(file2.exists()==真)
{
}其他
{
Log.v(目录中创建,新目录);
file2.mkdir();
}
/ **从URL中提取PDF FILNAME ** /
INT slashIndex = pdf.lastIndexOf('/');
INT dotIndex = pdf.lastIndexOf('。');
filenameWithExtension = pdf.substring(slashIndex + 1);
DownloadFile downloadFile =新DownloadFile(filenameWithExtension);
downloadFile.execute(PDF);
}
私有类DownloadFile扩展的AsyncTask<字符串,整数,字符串> {
字符串文件名=;
公共DownloadFile(字符串_filename){
this.filename = _filename;
}
字符串PATH = Environment.getExternalStorageDirectory()+/图片/+文件名;
文件filecheck =新的文件(路径);
@覆盖
保护字符串doInBackground(字符串... STR){
Log.v(文件名,this.filename);
如果(filecheck.exists()){
Log.v(中,如果条件,文件是alredy存在);
}其他{
Log.v(在其他条件,文件没有present ......);
尝试 {
网址URL =新的URL(海峡[0]);
HttpURLConnection的C =(HttpURLConnection类)url.openConnection();
c.setRequestMethod(GET);
c.setDoOutput(真正的);
c.connect();
//这将是有益的,这样就可以显示一个典型的0-100%的进度条
INT lenghtOfFile = c.getContentLength();
// downlod文件
// InputStream的输入=新的BufferedInputStream(url.openStream());
//的OutputStream输出=新的FileOutputStream(/ SD卡/地方/ nameofthefile.ext);
字符串PATH = Environment.getExternalStorageDirectory()+/图片/;
Log.v(log_tag,路径:+路径);
档案文件=新的文件(路径);
布尔查= filecheck.createNewFile();
Log.v(检查文件的创建.. ::,check.toString());
如果(file.mkdirs()==假)
{
Log.v(文件alredy存在SD卡,存在的文件);
}其他
{
Log.v(文件是在卡创建,新目录);
file.mkdirs();
}
文件OUTPUTFILE =新的文件(文件,filenameWithExtension);
FileOutputStream中FOS =新的FileOutputStream(OUTPUTFILE);
InputStream的是= c.getInputStream();
总长= 0;
byte []的缓冲区=新的字节[1024];
INT LEN1 = 0;
而((LEN1 = is.read(缓冲液))!= - 1){
共有+ = LEN1;
publishProgress((int)的(总* 100 / lenghtOfFile));
fos.write(缓冲液,0,LEN1);
}
fos.close();
is.close();
}赶上(IOException异常E){
Log.d(背景log_tag,错误:+ E);
}
}
Log.v(在aync任务的文件扩展名,filenameWithExtension);
返回filenameWithExtension;
}
您可以检查是否文件存在与否使用<一个href="http://download.oracle.com/javase/1.4.2/docs/api/java/io/File.html#exists%28%29"><$c$c>File.exists()$c$c>
文件f =新的文件(filePathString);
如果(f.exists())
{
/* 干点什么 */
}
其他
{
file.mkdirs();
//而你的其他东西放在这里
}
注意:存在()
将返回true目录,也
如果您要检查存在与否,你必须使用一个特定文件<一个href="http://download.oracle.com/javase/1.4.2/docs/api/java/io/File.html#isFile%28%29"><$c$c>File.isFile()$c$c>
布尔FILEEXISTS =新的文件(路径/到/ file.txt的)ISFILE()。
新建文件(C:/)存在()
将返回true,但不会让你打开并从中读出一个文件。
在你的code的问题是你的文件名是空。
编辑2:
试试这个:
字符串文件名=;
字符串PATH =;
文件fileCheck = NULL;
公共DownloadFile(字符串_filename){
this.filename = _filename;
PATH = Environment.getExternalStorageDirectory()+/图片/+文件名;
filecheck =新的文件(路径);
}
或
或上的AsyncTask的preExecute(),您就把这两个语句
PATH = Environment.getExternalStorageDirectory()+/图片/+文件名;
filecheck =新的文件(路径);
I want to download pdf from server and store on sdcard. I try something like following code but it will not go in else condition, as I am not created a file still it will giving MSG as file exist. Why is it so??
String pdf;
String filenameWithExtension="";
protected void onCreate(Bundle savedInstanceState) {
Intent intent=getIntent();
pdf=intent.getStringExtra("pdfurl");
String PATH2 = Environment.getExternalStorageDirectory()+"/pictures";
Log.v("log_tag initial path", "PATH: " + PATH2);
File file2 = new File(PATH2);
if(file2.exists()==true)
{
}else
{
Log.v("directory is created", "new dir");
file2.mkdir();
}
/**extracting the pdf filname from url**/
int slashIndex = pdf.lastIndexOf('/');
int dotIndex = pdf.lastIndexOf('.');
filenameWithExtension=pdf.substring(slashIndex + 1);
DownloadFile downloadFile = new DownloadFile(filenameWithExtension);
downloadFile.execute(pdf);
}
private class DownloadFile extends AsyncTask<String, Integer, String>{
String filename="";
public DownloadFile(String _filename) {
this.filename=_filename;
}
String PATH = Environment.getExternalStorageDirectory()+"/pictures/"+filename;
File filecheck=new File(PATH);
@Override
protected String doInBackground(String... str) {
Log.v("name of file",this.filename);
if(filecheck.exists()){
Log.v("in if condition", "file is alredy exist");
}else{
Log.v("in else condition","file not present....");
try {
URL url = new URL(str[0]);
HttpURLConnection c = (HttpURLConnection)url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
// this will be useful so that you can show a typical 0-100% progress bar
int lenghtOfFile = c.getContentLength();
// downlod the file
// InputStream input = new BufferedInputStream(url.openStream());
//OutputStream output = new FileOutputStream("/sdcard/somewhere/nameofthefile.ext");
String PATH = Environment.getExternalStorageDirectory()+ "/pictures/";
Log.v("log_tag", "PATH: " + PATH);
File file = new File(PATH);
Boolean check=filecheck.createNewFile();
Log.v("check file creation..::", check.toString());
if(file.mkdirs()==false)
{
Log.v("file is alredy exist in sdcard", "exist file");
}else
{
Log.v("file is created in card", "new dir");
file.mkdirs();
}
File outputFile = new File(file,filenameWithExtension);
FileOutputStream fos = new FileOutputStream(outputFile);
InputStream is = c.getInputStream();
long total = 0;
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
total +=len1;
publishProgress((int)(total*100/lenghtOfFile));
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
} catch (IOException e) {
Log.d("log_tag of background", "Error: " + e);
}
}
Log.v("In aync task filename extension",filenameWithExtension);
return filenameWithExtension;
}
You can check whether File exists or not by using File.exists()
File f = new File(filePathString);
if(f.exists())
{
/* do something */
}
else
{
file.mkdirs();
//And your other stuffs goes here
}
Note : exists()
will return true for directories, too
If you want to check for a particular file that exists or not you have to use File.isFile()
boolean fileExists = new File("path/to/file.txt").isFile();
new File("C:/").exists()
will return true but will not allow you to open and read from it as a file.
The problem in your code is your filename is null.
Edit 2 :
Try this :
String filename="";
String PATH="";
File fileCheck=null;
public DownloadFile(String _filename) {
this.filename=_filename;
PATH = Environment.getExternalStorageDirectory()+"/pictures/"+filename;
filecheck=new File(PATH);
}
Or
or in onPreExecute() of AsyncTask you put this two statements
PATH = Environment.getExternalStorageDirectory()+"/pictures/"+filename;
filecheck=new File(PATH);
这篇关于如何存在与否,如果没有建立在SD卡中的异步任务的新文件,检查文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!