-1

I think this question may be a duplicate but I didn't find any other answers for this.

My question is:

Is it possible to know whether a file (e.g.: a .txt/.doc/.csv file) exists or not in any location (i.e. internal/external storage) in the device?

user2340612
  • 10,053
  • 4
  • 41
  • 66
syam vakkalanka
  • 426
  • 3
  • 15

3 Answers3

0

If you already know the path of the file you can use the following code:

File yourFile = new File(yourFilePath);
yourFile.exists();
user2340612
  • 10,053
  • 4
  • 41
  • 66
Niza Siwale
  • 2,390
  • 1
  • 18
  • 20
0

Hope it works in your case.

File file = new File(Environment.getExternalStorageDirectory() + File.separator + "filename with extention");
File file2 = new File("internal sotrage path here" + File.separator + "filename with extention");
try {
    if(file.exists()){
        // code if file exist in external storage
    }
    else if(file2.exists()){
        // code if file exist in internal storage
    }
    else {
        // file not found
    }
} catch (IOException e) {
    e.printStackTrace();
}
Pang
  • 9,564
  • 146
  • 81
  • 122
Khizar Hayat
  • 3,427
  • 3
  • 18
  • 22
0
 Future<String?> _saveFileToDevice(String filename, List<int> data) async {
// Get the path to the app's documents directory
var status = await Permission.storage.status;
if (!status.isGranted) {
  await Permission.storage.request();
}

var dir = Platform.isAndroid
    ? '/storage/emulated/0/Download'
    : (await getApplicationDocumentsDirectory()).path;

// Create the file and write the data to it
var file = File('$dir/$filename');

bool alreadyDownloaded = await file.exists();

String incrementCount(String fileName) {
  int dotIndex = fileName.lastIndexOf('.');
  String newFileName = fileName.substring(0, dotIndex) +
      "(${count += 1})" +
      fileName.substring(dotIndex);

  return newFileName;
}

if (alreadyDownloaded) {
  String newFileName = incrementCount(file.path);

  var newFile = File('$newFileName');
  await newFile.writeAsBytes(data, flush: true);

  String subStringFileName = newFileName.substring(29);
  CommonWidgets.makeToast(
      fontSize: 14,
      toastMsg: '${subStringFileName} saved to Downloads Folder');

  file = newFile;
  print('modified updating ....--> $file');
} else {
  await file.writeAsBytes(data, flush: true);

  CommonWidgets.makeToast(
      fontSize: 14,
      toastMsg: '${filename} saved to Downloads Folder');
}

return 'file://${file.path}';
}

Data is Uint8List Bytes which can convert the file into bytes and pass the byteslist