Я пытаюсь реализовать кнопку для просмотра файла и его копирования в папку «загрузки». Я использовал это решение для этого. Пожалуйста, посмотрите мой код здесь:
public void browseFile(View view) {
Intent chooseFile = new Intent(Intent.ACTION_GET_CONTENT);
chooseFile.addCategory(Intent.CATEGORY_OPENABLE);
chooseFile.setType("*/*");
startActivityForResult(
Intent.createChooser(chooseFile, "Choose a file"),
PICKFILE_RESULT_CODE
);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
File destination = null;
File source = null;
if (requestCode == PICKFILE_RESULT_CODE && resultCode == Activity.RESULT_OK) {
Uri content_describer = data.getData();
String src = content_describer.getPath();
source = new File(src);
Log.d("src is ", source.toString());
String filename = content_describer.getLastPathSegment();
//text.setText(filename);
Log.d("FileName is ", filename);
destination = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath() + File.separator + "/GSW/" + filename);
Log.d("Destination is ", destination.toString());
//SetToFolder.setEnabled(true);
}
try {
copy(source, destination);
} catch (IOException e) {
e.printStackTrace();
}
}
Я использую функцию копирования, как указано в решении, чтобы скопировать файл в папку назначения, как показано ниже:
private void copy(File src, File dest) throws IOException {
FileChannel in = new FileInputStream(src).getChannel();
FileChannel out = new FileOutputStream(dest).getChannel();
try {
in.transferTo(0, in.size(), out);
} catch(Exception e){
Log.d("Exception", e.toString());
} finally {
if (in != null)
in.close();
if (out != null)
out.close();
}
}
Я пробовал много других решений дано, но я все еще получаю «FileNotFoundException», как показано ниже:
Ошибка
W / System.err: java .io.FileNotFoundException: / document / primary: WhatsApp / Media / WhatsApp Documents / IGN Holiday List 2020.pdf (нет такого файла или каталога) W / System.err: в java .io.FileInputStream.open0 (собственный метод)
РЕДАКТИРОВАТЬ 1
Я обновил свой код в соответствии с предложением @blackapps Все еще получаю исключение FileNotFoundException, но на этот раз с адресатом.
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Uri content_describer = data.getData();
InputStream in = null;
OutputStream out = null;
try {
// open the user-picked file for reading:
in = getContentResolver().openInputStream(content_describer);
// open the output-file:
out = new FileOutputStream(new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath() + "/GSW/" + File.separator));
// copy the content:
byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
// Contents are copied!
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (out != null){
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Ошибка
2020-02-12 17: 07: 09.214 5412-5412 / com.gsw.nf c W / System.err: java .io.FileNotFoundException: / storage / emulated / 0 / Download / GSW (является каталогом) 2020-02-12 17: 07: 09.215 5412-5412 / com.gsw.nf c W / System.err : at java .io.FileOutputStream.open0 (собственный метод)