2

I have a small Java code in Android Studio. I run it in emulator (Android 7.1.1 API 25).

How I validate a file name and file name length?

Should I check the length with path name or only file name!

I found Android support 255 character as a file name.

File name text in Language Bengali (UNICODE UTF-8)

File downloadFile = new File("/storage/emulated/0/MyDownload/আমার সোনার বাংলা আমি তোমায় ভালোবাসি চিরদিন তোমার আকাশ তোমার বাতাস আমার প্রাণে বাজায় বাঁশি ও মা ফাগুনে তোর.mp4");
FileOutputStream outputStream = new FileOutputStream(downloadFile, true);
downloadFile.toString().length() // OUTPUT: 142

ERROR: java.io.FileNotFoundException: /storage/emulated/0/MyDownload/আমার সোনার বাংলা আমি তোমায় ভালোবাসি চিরদিন তোমার আকাশ তোমার বাতাস আমার প্রাণে বাজায় বাঁশি ও মা ফাগুনে তোর.mp4 (File name too long)

2
  • You do not have access to files in Downloads/ on Android 11+, unless your app is the one that downloaded it. Please consider using the Storage Access Framework (ACTION_OPEN_DOCUMENT / ActivityResultContracts.OpenDocument) instead. Commented Sep 24, 2022 at 15:09
  • it has file access File downloadFile = new File("/storage/emulated/0/MyDownload/abcd.mp4"); FileOutputStream outputStream = new FileOutputStream(downloadFile, true); it works and file write is ok Commented Sep 24, 2022 at 15:11

1 Answer 1

3
String name = "আমার-সোনার-বাংলা-আমি-তোমায়-ভালোবাসি-চিরদিন-তোমার-আকাশ-তোমার-বাতাস-আমার-প্রাণে-বাজায়-বাঁশি-ও-মা-ফাগুনে-তোর.mp4";
final byte[] utf8Bytes = name.getBytes(StandardCharsets.UTF_8);
if(utf8Bytes.length > 255) {
    name = new String(Arrays.copyOfRange(utf8Bytes, 0, 255), StandardCharsets.UTF_8);
}
System.out.println(name);
Sign up to request clarification or add additional context in comments.

2 Comments

It works but it cut the file extension. I will manage it. Thanks anyway @ABHIJIT, at last found a good way. Love you ... ...
yes, you just split extension name and cut file name to 255 bytes

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.