Check if file exists on Android device with Kotlin - file

I'm newbie in Android development and doing on my first Android project and faced with .txt file handling.
I succesfully created a txt file on Android Emulator, which is stored in: /storage/emulated/0/Android/data/com.example.test/files/test.txt
My problem is, I don't know how to test with code if this file exists. I write next few lines, which I found on the Internet:
fun checkIfFileExists() {
val fileName2 = "test.txt"
var file = File(filesDir, fileName2)
var fileExists = file.exists()
if(fileExists) {
println("File exists")
}
else {
println("File doesn't exists")
}
}
Function for file saving:
btnSave.setOnClickListener(View.OnClickListener {
val file:String = fileName.text.toString()
val data:String = fileData.text.toString()
val fileOutputStream:FileOutputStream
try {
fileOutputStream = openFileOutput(file, Context.MODE_PRIVATE)
fileOutputStream.write(data.toByteArray())
}catch (e: FileNotFoundException){
e.printStackTrace()
}catch (e: NumberFormatException){
e.printStackTrace()
}catch (e: IOException){
e.printStackTrace()
}catch (e: Exception){
e.printStackTrace()
}
Toast.makeText(applicationContext,"data save",Toast.LENGTH_LONG).show()
fileName.text.clear()
fileData.text.clear()
})
But it always prints "File doesn't exists", although I checked myself and file exists.
Hope someone knows what I did wrong.

You instantiated the file with only the file name and no path, so how can it know where to look? On Android you don't want to be working with the absolute paths but with what the Context gives you.
Not sure how you created your original file, but assuming it was saved to internal storage, you would do this (getFilesDir() is a Context method, so will be available if calling from an Activity):
var file = File(getFilesDir().getAbsolutePath(), fileName2)

Related

How to fix "FileSystemException: Cannot open file" in flutter when reading and writing files?

I'm pretty new to dart/flutter, so let me know if there is anything I can clarify. I'm trying to download a file, but when I try to access it, I get the error
FileSystemException: Cannot open file, path = './data.csv' (OS Error: Read-only file system, errno = 30)
What am I doing wrong, and how can I fix this?
downloadTextFile() {
HttpClient client = new HttpClient();
client.getUrl(Uri.parse('I put the link I used here, but it is sort of long'))
.then((HttpClientRequest request) {
return request.close();
})
.then((HttpClientResponse response) {
response.pipe(new File('./data.csv').openWrite());
});
readFileByLines();
}
void readFileByLines() {
File file = new File('./data.csv');
List<String> lines = file.readAsLinesSync();
lines.forEach((l) => print(l));
}
You can use package https://pub.dev/packages/path_provider
And write your file to tempPath or appDocPath
Directory tempDir = await getTemporaryDirectory();
String tempPath = tempDir.path;
Directory appDocDir = await getApplicationDocumentsDirectory();
String appDocPath = appDocDir.path;
For Android , In AndroidManifest.xml , you can add permission
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

How to get last downloaded file using selenium

Is there anyway I can get the last downloaded file using selenium. Currently I am downloading an Excel file using selenium, I need to get that file and read it. the reading part is covered, but I need the downloaded file path and file name in order to read it. So far i haven't found anything which can help. I am looking mainly for a google chrome solution, but firefox works too.
Thanks in advance
You can save your download to a fix location by using the profile. Check these discussions:
Downloading file to specified location with Selenium and python
Access to file download dialog in Firefox
As you have mentioned that you have covered the reading part. You can read it from that fixed location.
Below is the code snippet that can help resolve the above query:
**Changes in driver file:**
protected File downloadsDir = new File("");
if (browser.equalsIgnoreCase("firefox"))
{
downloadsDir = new File(System.getProperty("user.dir") + File.separatorChar + "downloads");
if (!downloadsDir.exists())
{
boolean ddCreated = downloadsDir.mkdir();
if (!ddCreated) {
System.exit(1);
}
}
}
/*Firefox browser profile*/
FirefoxProfile firefoxProfile = new FirefoxProfile();
firefoxProfile.setPreference("browser.download.folderList", 2);
firefoxProfile.setPreference("browser.download.manager.showWhenStarting", false);
firefoxProfile.setPreference("browser.download.dir", downloadsDir.getAbsolutePath());
firefoxProfile.setPreference("browser.helperApps.neverAsk.saveToDisk", "text/plain,application/octet-stream");
**Empty the download directory[Can be implemented as #BeforeClass]:**
public void emptyDownloadsDir()
{
// Verify downloads dir is empty, if not remove all files.
File[] downloadDirFiles = downloadsDir.listFiles();
if (downloadDirFiles != null) {
for (File f : downloadDirFiles) {
if (f.exists()) {
boolean deleted = FileUtility.delete(f);
assertTrue(deleted, "Files are not deleted from system local directory" + downloadsDir + ", skipping the download tests.");
}
}
}
}
**Check the Latest downloaded file:**
/*Test file*/
protected static String EXCEL_FILE_NAME= Test_Excel_File.xls;
protected static int WAIT_IN_SECONDS_DOWNLOAD = 60;
// Wait for File download.
int counter = 0;
while (counter++ < WAIT_IN_SECONDS_DOWNLOAD && (downloadsDir.listFiles().length != 1 || downloadsDir.listFiles()[0].getName().matches(EXCEL_FILE_NAME))) {
this.wait(2);
}
// Verify the downloaded File by comparing name.
File[] downloadDirFiles = downloadsDir.listFiles();
String actualName = null;
for (File file : downloadDirFiles) {
actualName = file.getName();
if (actualName.equals(EXCEL_FILE_NAME)) {
break;
}
}
assertEquals(actualName, EXCEL_FILE_NAME, "Last Downloaded File name does not matches.");
import os
import glob
home = os.path.expanduser("~")
downloadspath=os.path.join(home, "Downloads")
list_of_files = glob.glob(downloadspath+"\*.pptx") # * means all if need specific format then *.csv
latest_file = max(list_of_files, key=os.path.getctime)
Simplified solution to get the path to last file in Downloads folder. The above code will get path of the latest .pptx file in Downlodas. Change the extension as required. Or else you can chose not to specify the extension
Note, Shared answer is specific to Chrome Browser and will ONLY return LATEST downloaded file. But we can modify accordingly it for other browsers and for all files as well.
Let say, how we test latest downloaded file in browser.
In existing test browser Open NewTab Window
Go to
downloads (chrome://downloads/)
Check if expected file is there
or not
Now same thing in selenium using java
driver.get("chrome://downloads/");
JavascriptExecutor js = (JavascriptExecutor) driver;
WebElement element = (WebElement) js.executeScript("return document.querySelector('downloads-manager').shadowRoot.querySelector('#mainContainer > iron-list > downloads-item').shadowRoot.querySelector('#content')");
String latestFileName= element.getText();

Getting path of audio file from sdcard

In my app I tried to pass the file path from one activity to another activity using intent.In my receiving activity I got the file path as "null".But when I print the file in first activity it prints the path.From my second activity I attach that file to mail using Gmailsender.This was the code I tried,
private void startRecord()
{
File file = new File(Environment.getExternalStorageDirectory(), "test.pcm");
try
{
file.createNewFile();
OutputStream outputStream = new FileOutputStream(file);
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream);
DataOutputStream dataOutputStream = new DataOutputStream(bufferedOutputStream);
int minBufferSize = AudioRecord.getMinBufferSize(8000,
AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT);
short[] audioData = new short[minBufferSize];
AudioRecord audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC,
8000,
AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT,
minBufferSize);
audioRecord.startRecording();
while(recording)
{
int numberOfShort = audioRecord.read(audioData, 0, minBufferSize);
for(int i = 0; i < numberOfShort; i++)
{
dataOutputStream.writeShort(audioData[i]);
}
}
audioRecord.stop();
audioRecord.release();
dataOutputStream.close();
}
catch (IOException e)
{
e.printStackTrace();
}
String audiofile;
audiofile=file.getAbsolutePath();
System.out.println("File Path::::"+audiofile);
}
Intent is,
Intent sigout=new Intent(getApplicationContext(),WeeklyendActivity.class);
sigout.putExtra("mnt/sdcard-test.pcm",audiofile);
startActivity(sigout);
In my receiving activity,
String patty=getIntent().getStringExtra("mnt/sdcard-text.pcm");
System.out.println("paathhhy frfom ::"+patty);
It prints null.Can anyone help me how to get the file path.And more thing I am not sure whether the audio would save in that file correctly?
Please anyone help me!!!Thanks in advance!
Based on your information that audioFile is a variable of type File, when you do this:
sigout.putExtra("mnt/sdcard-test.pcm",audiofile);
you are putting a File object in the extras Bundle. Then, when you try to get the extra from the Bundle you do this:
String patty=getIntent().getStringExtra("mnt/sdcard-text.pcm");
However, the object in this extra is of type File, not type String. This is why you are getting null.
If you only want to pass the name of the file, then put the extra like this:
sigout.putExtra("mnt/sdcard-test.pcm",audiofile.getAbsolutePath());

Windows 8 StorageFile.GetFileFromPathAsync Using UNC Path

Has anyone EVER managed to use a windows 8 app to copy files from a unc dir to a local dir ?
According to the official documentation here
It is possible to connect to a UNC path
I am using the std FILE ACCESS sample and have changed one line of code to read as below
I have added all the capabilities
Added .txt as a file type
The UNC path is read write to everyone and is located on the same machine..
But I keep getting Access Denied Errors.
Can anyone possibly provide me with a working example
This is driving me mad and really questioning the whole point of win 8 dev for LOB apps.
TIA
private async void Initialize()
{
try
{
//sampleFile = await Windows.Storage.KnownFolders.DocumentsLibrary.GetFileAsync(filename);
string myfile = #"\\ALL387\Temp\testfile.txt";
sampleFile = await Windows.Storage.StorageFile.GetFileFromPathAsync(myfile);
}
catch (FileNotFoundException)
{
// sample file doesn't exist so scenario one must be run
}
catch (Exception e)
{
var fred = e.Message;
}
}
I have sorted this out and the way I found best to do it was to create a folder object
enumnerate over the files in the folder object
copy the files one at a time to the local folder then access them
It seems that you can't open the files, but you can copy them. ( which was what I was trying to achieve in the first place )
Hope this helps
private async void Initialize()
{
try
{
var myfldr = await Windows.Storage.StorageFolder.GetFolderFromPathAsync(#"\\ALL387\Temp");
var myfiles = await myfldr.GetFilesAsync();
foreach (StorageFile myfile in myfiles)
{
StorageFile fileCopy = await myfile.CopyAsync(KnownFolders.DocumentsLibrary, myfile.Name, NameCollisionOption.ReplaceExisting);
}
var dsd = await Windows.Storage.KnownFolders.PicturesLibrary.GetFilesAsync();
foreach (var file in dsd)
{
StorageFile sampleFile = await Windows.Storage.StorageFile.GetFileFromPathAsync(file.Path);
}
}
catch (FileNotFoundException)
{
// sample file doesn't exist so scenario one must be run
}
catch (Exception e)
{
var fred = e.Message;
}
}

get email attatchment for POP 3 received as winmail.dat

When I try to get attatchment from POP 3 mail, I am getting them as winmail.dat, not the original attached file name. How can I get the original file name?
for (int i = 0; i < multipart.getCount(); i++)
{
BodyPart bodyPart = multipart.getBodyPart(i);
if(!Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition()))
{
//do something
}
else
{
bodyPart.getFileName(); // here only get the winmail.dat
}
}
This is part of the Exchange Settings, and sadly you going to need to extract the original contents from the WinMail.dat using JTNEF.
"The Java TNEF package is an open source code implementation of a TNEF message handler, which can be used as a command-line utility or integrated into Java-based mail applications to extract the original message content."
This is found on the JavaMail's third party tools.
As alternative and what looks simpler is POI-HMEF
Sample extraction:
public void extract(String winmailFilename, String directoryName) throws Exception {
HMEFContentsExtractor ext = new HMEFContentsExtractor(new File(winmailFilename));
File dir = new File(directoryName);
File rtf = new File(dir, "message.rtf");
if(! dir.exists()) {
throw new FileNotFoundException("Output directory " + dir.getName() + " not found");
}
System.out.println("Extracting...");
ext.extractMessageBody(rtf);
ext.extractAttachments(dir);
System.out.println("Extraction completed");
}
There is also a sample for printing the contents here.

Resources