blob: 4847ac256d11c3fadb7824969ffa685586473d87 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
|
package it.niedermann.nextcloud.deck.util;
import android.content.Context;
import android.net.Uri;
import androidx.annotation.NonNull;
import androidx.annotation.WorkerThread;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import it.niedermann.nextcloud.deck.DeckLog;
/**
* Created by stefan on 07.03.20.
*/
public class FilesUtil {
private FilesUtil() {
}
/**
* https://help.nextcloud.com/t/android-app-select-file-with-nextcloud-app-file-cant-be-read/103706
* Must not be called from the UI thread because the {@param currentUri} might refer to a not yet locally available file.
*/
@WorkerThread
public static File copyContentUriToTempFile(@NonNull Context context, @NonNull Uri currentUri, long accountId, Long localCardId) throws IOException, IllegalArgumentException {
final InputStream inputStream = context.getContentResolver().openInputStream(currentUri);
if (inputStream == null) {
throw new IOException("Could not open input stream for " + currentUri.getPath());
}
final File cacheFile = getTempCacheFile(context, "attachments/account-" + accountId + "/card-" + (localCardId == null ? "pending-creation" : localCardId) + '/' + UriUtils.getDisplayNameForUri(currentUri, context));
final FileOutputStream outputStream = new FileOutputStream(cacheFile);
byte[] buffer = new byte[4096];
int count;
while ((count = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, count);
}
DeckLog.verbose("----- wrote");
return cacheFile;
}
/**
* Creates a new {@link File}
*/
public static File getTempCacheFile(@NonNull Context context, String fileName) throws IOException {
File cacheFile = new File(context.getApplicationContext().getFilesDir().getAbsolutePath() + "/" + fileName);
DeckLog.verbose("- Full path for new cache file: " + cacheFile.getAbsolutePath());
final File tempDir = cacheFile.getParentFile();
if (tempDir == null) {
throw new FileNotFoundException("could not cacheFile.getParentFile()");
}
if (!tempDir.exists()) {
DeckLog.verbose("-- The folder in which the new file should be created does not exist yet. Trying to create it...");
if (tempDir.mkdirs()) {
DeckLog.verbose("--- Creation successful");
} else {
throw new IOException("Directory for temporary file does not exist and could not be created.");
}
}
DeckLog.verbose("- Try to create actual cache file");
if (cacheFile.createNewFile()) {
DeckLog.verbose("-- Successfully created cache file");
} else {
throw new IOException("Failed to create cacheFile");
}
return cacheFile;
}
}
|