gpt4 book ai didi

android - 如何检查文件是否存在,如果不存在则在异步任务中的 sdcard 中创建一个新文件

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:53:13 25 4
gpt4 key购买 nike

我想从服务器下载 pdf 并存储在 sdcard 上。我尝试了类似以下代码的方法,但它不会进入其他条件,因为我没有创建文件,它仍然会在文件存在时提供 MSG。为什么会这样??

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;
}

最佳答案

您可以使用File.exists() 检查文件是否存在。

   File f = new File(filePathString);
if(f.exists())
{
/* do something */
}
else
{
file.mkdirs();
//And your other stuffs goes here
}

注意:exists() 也会为目录返回 true

如果你想检查一个特定的文件是否存在,你必须使用 File.isFile()

boolean fileExists =  new File("path/to/file.txt").isFile();

new File("C:/").exists() 将返回 true 但不允许您将其作为文件打开和读取。

您的代码中的问题是您的文件名是空的。

编辑 2:

试试这个:

String filename="";
String PATH="";
File fileCheck=null;

public DownloadFile(String _filename) {
this.filename=_filename;
PATH = Environment.getExternalStorageDirectory()+"/pictures/"+filename;
filecheck=new File(PATH);
}

或者

或者在 AsyncTask 的 onPreExecute() 中放置这两个语句

      PATH = Environment.getExternalStorageDirectory()+"/pictures/"+filename;
filecheck=new File(PATH);

关于android - 如何检查文件是否存在,如果不存在则在异步任务中的 sdcard 中创建一个新文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7817551/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com