Kotlin: Cannot get FileReader to find file - android

For an Android App, I'm trying to use the FilerReader function to read my csv file, but after trying everything I cannot get to find my file. I'm using Android studios on a Mac.
Below is my code inside OnCreate():
val filereader = BufferedReader(FileReader("sgsraagadata.csv"))
I have tried placing the csv file inside assets & all resource folders including a raw-type folder.
Similar posts on Stackoverflow suggests that I find the directory that is being searched so that I can put the csv file in that directory. But when I follow their instructions below is what I get.
When I use:
println(System.getProperty("user.dir"))
It prints "/". And when I use:
println(File(".").getAbsoluteFile())
It prints "/."
Given these printed outputs, where should I put the csv file?
*Also added an image showing csv file in assets folder as per suggestion in comments. Result is still an file not found error.

Put your file in assets folder and open it like this:
val file = context.assets.open("sgsraagadata.csv")
val isr = InputStreamReader(file)
val reader = BufferedReader(isr)
var line = reader.readLine()
while (line != null) {
// do something with the line
line = reader.readLine()
}
supply a valid Context or inside an activity you can omit it.

Related

Reading and existing file in Xamarin withC#

This code works:
string file = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "File.text");
File.ReadAllText(file);
Pretty straight-forward, but when I display the variable "file" using a Pizel 5 simulator I get a weird path: /data/user/0/com.companyname.aikidohours/files/.local/share/File.text. I can write new data to the file and read from it. but I now want to read from an existing file and I can't figure out where to put the file. Can someone tell where to put a text file full of basic information that I need to read from in Xamarin for adnroid?
Thanks
Todd
If you want to deploy that file with your application, you can add it to the 'Assets' folder inside your_project_name.Android project.
WARNING!!! File put in this folder are READONLY!
In case this is ok for you,this is the code to access the file:
using Xamarin.Essentials;
using (var reader = new StreamReader(await FileSystem.OpenAppPackageFileAsync("file_path")))
{
string content = reader.ReadToEnd();
}

Why can't Android Studio read the entire contents of my unzipped docx xml file?

I'm using an InputFileStream in a BufferedReader to get lines of data out of an XML I unzipped out of a zip file:
iStream = mContext.assets.open("files/word/document.xml")
val reader = BufferedReader(InputStreamReader(iStream))
var line = reader.readLine()
for (i in 0..50) {
Log.d("Trace", line)
line = reader.readLine()
}
For some reason Android IDE is only able to read a few lines from the stream even through the xml file has hundreds of lines. If I open the file in a window in the IDE, it is the same story.
Can anyone tell me how to get ahold of the data here?

Kotlin: How to create/append file (and share)

I have a list of arrays of data in my app that I would now like to write to a file (csv) and use a 3rd party app (such as email) to share this csv file. I have had no luck finding any helpful resources for creating, finding the file path for, and appending to a file in Kotlin. Does anyone have experience with this or have examples to point to? Just to get started I'm trying to write the header and close the file so I can see that it is correctly writing.
This is what I have for now:
val HEADER = "ID, time, PSI1, PSI2, PSI3, speed1, speed2, temp1, temp2"
val filename = "export.csv"
var fileOutStream : FileOutputStream = openFileOutput(filename,Context.MODE_PRIVATE)
try {
fileOutStream.write(HEADER.toByteArray())
fileOutStream.close()
}catch(e: Exception){
Log.i("TAG", e.toString())
}
It doesn't throw the exception, but I cannot find the file in the file system. I'm using a physical tablet for testing/debug. I've checked the com.... folder for my app.
I cannot find the file in the file system
Use Android Studio's Device File Explorer and look in /data/data/.../files/, where ... is your application ID.
Also, you can write your code a bit more concisely as:
try {
PrintWriter(openFileOutput(filename,Context.MODE_PRIVATE)).use {
it.println(HEADER)
}
} catch(e: Exception) {
Log.e("TAG", e.toString())
}
use() will automatically close the PrintWriter, and PrintWriter gives you a more natural API for writing out text.
It appears there are many ways to create a file and append to it, depending on the minimum API version you are developing for. I am using minimum Android API 22. The code to create/append a file is below:
val HEADER = "DATE,NAME,AMOUNT_DUE,AMOUNT_PAID"
var filename = "export.csv"
var path = getExternalFilesDir(null) //get file directory for this package
//(Android/data/.../files | ... is your app package)
//create fileOut object
var fileOut = File(path, filename)
//delete any file object with path and filename that already exists
fileOut.delete()
//create a new file
fileOut.createNewFile()
//append the header and a newline
fileOut.appendText(HEADER)
fileOut.appendText("\n")
/*
write other data to file
*/
openFileOutput() creates a private file, likely inside of app storage. These files are not browsable by default. If you want to create a file that can be browsed to, you'll need the WRITE_EXTERNAL_STORAGE permission, and will want to create files into a directory such as is provided by getExternalFilesDir()

Get preloaded file in android

I'm new to android development and I am working on a little project. What I am having some issue with is getting access to preloaded files.
In my app, I have an XML file that I preloaded (I just simply put it in my src folder in a package). How do I access them in my classes? I need to get a File object pointing to this file so that I can use it as I would I/O files. It seems like this should be trivial, but alas I am stuck.
Lets say the file is located under: com.app.preloadedFiles/file1.XML
I've tried something along the lines of this, but have had no success:
URL dir_url = ClassLoader.getSystemResource("preloadedFiles/file1.XML");
FIle file = new File(dir_url.toURI());
I solved this in my app by getting an InputStream to the file -- something like:
myContext.getAssets().open(fileName);
//read the data and store it in a variable
Then, if you truly need to do File related opterations with it, you can write it to a private (or public) directory and do your operations from you newly written file. Something like:
File storageDir = myContext.getDir(directoryName, Context.MODE_PRIVATE);
File myFile = new File(storageDir + File.separator + fileName);
//then, write the data to the file and manipulate it -- store the name for access via File later

FileNotFoundException in an Android app: can't find the route to copy the file

Good afternoon everyone,
I'm having a problem here with an CSV file that I wanna use to fill a dynamic table in Android.
I placed the file in the "data" folder of my emulator, and I did the following declaration to create my file variable:
file = new File("/data/Motors.csv");
I used a CSVReader class posted on another thread from this page (Link to the class) and also declared the following line to do the parse:
readerCSV = new CSVReader(new FileReader(file),';','"',0);
In the last line, the programmer to be able to create the variable has to send as parameters a Reader (Or a FileReader, it doesn't make a difference), the separator char, the quote char and the number of how many lines the CSV reader has to skip.
The problem comes that no matter in which directory (Not even in the root directory, which Java tells me that it's "/" through the file.getAbsolutePath(); method) it always gets to the point when the program throws the FileNotFoundException and I'm getting a bit frustrated because I have 2 days already with this problem.
If someone could please help me to get a bit of orientation of what I should do to get the file from the right directory... It would be a lot of help and I can go further with the code I have to finish.
Many thanks in advance!!!!
EDIT
I found a solution to open my file:
I have used 2 file variables: one gets the rout of the External Storage Directory (see first answer in the following link) and the other is declared as a new file, like the following lines in the code:
route = Environment.getExternalStorageDirectory();
file = new File(route,"Motors.csv");
Later I used again the CSV reader class that I found, where the first parameter is from the FileReader type (Sorry #Rajesh, but I couldn't use your alternative because you passed a FileDescription parameter from the AssetManager to the CSV reader class and then I had to change the whole class and that didn't help my problem at all).
Now I don't get the exception at all!!
There are various Storage Options in Android. Files can be stored in internal and external storages. If the CSV file is a static resource, you could think of bundling the file in the "assets" folder of your project.
If you are using the "assets" route, the following code segment can get you a CSVReader.
AssetManager am = getAssets();
AssetFileDescriptor afd = am.openFd ("Motors.csv");
FileDescriptor fd = afd.getFileDescriptor();
readerCSV = new CSVReader(fd, ';','"',0);
The above code snippet doesn't perform error/exception handling, please remember to take care of that. You need to copy the Motors.csv file to the "assets" folder within the project.

Categories

Resources