How to use Android Internal Storage? - java

I am a beginner in java and I am building an android app.
I want to have an xml file that has text in it.
Whenever the server sends updates, I want to change some lines in that file (what I mean by update is changing some lines in that file by erasing the some part of the text written already and replace by the update)
I know nothing about creating,writing or reading from files.
When I searched I found out that Internal storage suits me best.
But I do not know if I have to create an xml file manually in any directory or just use the code bellow to create this file automatically?
// If this is the first time run,execute one time code
// create XML Internal store
String FILENAME = "My_XML_file";
try{
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_APPEND);
} catch (final IOException e) {
e.printStackTrace();
}
Thank you in advance!

- First give the External Storage permission in the Manifest.xml file.
- You can use JAXP & JAXB, and even CASTOR to handle XML in a better way, but still DOM and SAX are inbuilt into Android.
You can use something like this
String s = "/sdcard/Myfolder/mytext.txt";
File f = new File(s);

The code you have will create a file in internal storage but you need a bit more to create and maintain an XML file easily.
I suggest you use the Build in Android DOM Parser (Android developers site docs on XML Parse options)
I found this example which explains how to use the dom parser to build a specific (new) XML file from code. In your context where the output stream in created:
StreamResult result = new StreamResult(new File("C:\\file.xml"));
you might want to use the other constructor based on the output stream you created above
StreamResult result = new StreamResult(fos);
In a similar fashion this DOM library allows you to read from an input stream (which you might get from android openFileInput) using DocumentBuilder.parse()

Related

Generate string content for CSV with Apache Commons in Java instead of writing an actual file

in my Java program, I would like to use the Apache Commons library to generate the content of a CSV file, but not actually creating the file.
I only want to have the String content of the file, and later, write the file using that content using an existing method.
However in all examples of code, it is necessary to define in the target csv file before hand, giving its path and name, but I don't have it, at this moment of the program flow.
Is it possible to just get the String for the future csv file, and handle the real file creation independently?
Thank you.
StringWriter
You need the file when you want to write to the file.
You could pass the file's content around your programm or store it somewhere until you want to write to the file.
However if you want to write your CSV to String and not to a File you could try to use a StringWriter instead of a FileWriter.
Something like (not compiled, might not be complete)
StringWriter stringWriter = new StringWriter();
CSVPrinter csvPrinter = new CSVPrinter(stringWriter , CSVFormat.DEFAULT
.withHeader("Header1", "Header2"));
csvPrinter.printRecord("abc", "ghf");
String csvString = stringWriter.toString();

Read and Append data to the File from a Blob URL path before download

This is my first hands on using Java Spring boot in a project, as I have mostly used C# and I have a requirement of reading a file from a blob URL path and appending some string data(like a key) to the same file in the stream before my API downloads the file.
Here are the ways that I have tried to do it:
FileOutputStream/InputStream: This throws a FileNotfoundException as it is not able to resolve the blob path.
URLConnection: This got me somewhere and I was able to download the file successfully but when I tried to write/append some value to the file before I download, I failed.
the code I have been doing.
//EXTERNAL_FILE_PATH is the azure storage path ending with for e.g. *.txt
URL urlPath = new URL(EXTERNAL_FILE_PATH);
URLConnection connection = urlPath.openConnection();
connection.setDoOutput(true); //I am doing this as I need to append some data and the docs mention to set this flag to true.
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
out.write("I have added this");
out.close();
//this is where the issues exists as the error throws saying it cannot read data as the output is set to true and it can only write and no read operation is allowed. So, I get a 405, Method not allowed...
inputStream = connection.getInputStream();
I am not sure if the framework allows me to modify some file in the URL path and read it simultaneously and download the same.
Please help me in understanding if they is a better way possible here.
From logical point of view you are not appending data to the file from URL. You need to create new file, write some data and after that append content from file from URL. Algorithm could look like below:
Create new File on the disk, maybe in TMP folder.
Write some data to the file.
Download file from the URL and append it to file on the disk.
Some good articles from which you can start:
Download a File From an URL in Java
How to download and save a file from Internet using Java?
How to append text to an existing file in Java
How to write data with FileOutputStream without losing old data?

Creating a .txt file from scratch

I'm working on a microcontroller and I'm trying to write some data from some sensors into a .txt file on the SDcard and later on place the sd card in a card reader and read the data on the PC.
Does anyone know how to write a .txt file from scratch for a FAT32 file system? I don't have any predefined code/methods/functions to call, I'll need to create the code from nothin.
It's not a question for a specific programming language, that is why I tagged more than one. I can later on convert the code from C or Java to my programming language of choice. But I can't seem to find such low level methods/functions in any type of language :)
Any ideas?
FatFs is quite good, and highly portable. It has support for FAT12, FAT16 and FAT32, long filenames, seeking, reading and writing (most of these things can be switched on and off to change the memory footprint).
If you're really tight on memory there's also Petit FatFs, but it doesn't have write support by default and adding it would take some work.
After mounting the drive you'd simply open a file to create it. For example:
FATFS fatFs;
FIL newFile;
// The drive number may differ
if (f_mount(0, &fatFs) != FR_OK) {
// Something went wrong
}
if (f_open(&newFile, "/test.txt", FA_WRITE | FA_OPEN_ALWAYS) != FR_OK) {
// Something went wrong
}
If you really need to create the file using only your own code you'll have to traverse the FAT, looking for empty space and then creating new LFN entries (where you store the filename) and DIRENTs (which specify the clusters on the disk that will hold the file data).I can't see any reason for doing this except if this is some kind of homework / lab exercise. In any case you should do some reading about the FAT structure first and return with some more specific questions once you've got started.
In JAVA you can do like this
Writer output = null;
String text = "This is test message";
File file = new File("write.txt");
output = new BufferedWriter(new FileWriter(file));
output.write(text);
output.close();
System.out.println("Your file has been written");

Input Stream from ZipResourceFile talking lot of time to read data

I have successfully implemented Apk Expansion Files for my project.
Problem:In my .obb i have a folder which has 100 xml files in it.Now the problem is i am using the below code to read the data directly from .obb files without extracting the data.
this is code given in the offical doc here http://developer.android.com/google/play/expansion-files.html under the topic Reading from a ZIP file
ZipResourceFile expansionFile = APKExpansionSupport.getAPKExpansionZipFile(MyActivity.this, 1, 0);
String pathToFileInsideZip = "main.1.com.my.expansionfiles.obb/data/" +filename;
InputStream fileStream = expansionFile.getInputStream(pathToFileInsideZip);
i have a for loop in that i am calling writing this code so that it will read all the xml one by one and make the data ready for me to display.
The above will read the data directly from .obb file, but the problem is its talking lot of time to extract the data?
Why so? i am doing any mistake here?
I believed that the pathToFileInsideZip would not be
main.1.com.my.expansionfiles.obb/data/[files].
I think it's just
"data/[files]"

Java- using an InputStream as a File

I'm trying to generate a PDF document from an uploaded ".docx" file using JODConverter.
The call to the method that generates the PDF is something like this :
File inputFile = new File("document.doc");
File outputFile = new File("document.pdf");
// connect to an OpenOffice.org instance running on port 8100
OpenOfficeConnection connection = new SocketOpenOfficeConnection(8100);
connection.connect();
// convert
DocumentConverter converter = new OpenOfficeDocumentConverter(connection);
converter.convert(inputFile, outputFile);
// close the connection
connection.disconnect();
I'm using apache commons FileUpload to handle uploading the docx file, from which I can get an InputStream object. I'm aware that Java.io.File is just an abstract reference to a file in the system.
I want to avoid the disk write (saving the InputStream to disk) and the disk read (reading the saved file in JODConverter).
Is there any way I can get a File object refering to an input stream? just any other way to avoid disk IO will also do!
EDIT: I don't care if this will end up using a lot of system memory. The application is going to be hosted on a LAN with very little to zero number of parallel users.
File-based conversions are faster than stream-based ones (provided by StreamOpenOfficeDocumentConverter) but they require the OpenOffice.org service to be running locally and have the correct permissions to the files.
Try the doc to avoid disk writting:
convert(java.io.InputStream inputStream, DocumentFormat inputFormat, java.io.OutputStream outputStream, DocumentFormat outputFormat)
There is no way to do it and make the code solid. For one, the .convert() method only takes two Files as arguments.
So, this would mean you'd have to extend File, which is possible in theory, but very fragile, as you are required to delve into the library code, which can change at any time and make your extended class non functional.
(well, there is a way to avoid disk writes if you use a RAM-backed filesystem and read/write from that filesystem, of course)
Chances are that commons fileupload has written the upload to the filesystem anyhow.
Check if your FileItem is an instance of DiskFileItem. If this is the case the write implementation of DiskFileItem willl try to move the file to the file object you pass. You are not causing any extra disk io then since the write already happened.

Categories