Android studio, open a file , continuously write and then close - java

I have code that is generating data every second and displaying onscreen.
This all works fine but I want to create a log file of all the data to analyze later.
I can open/write/close a file each time data is created but I am unsure of how much processing power this is using as it is continually opening and closing the file
String data= reading1","+reading2+","+time +"/n";
try {
FileOutputStream out = openFileOutput("data.csv", Context.MODE_PRIVATE);
out.write(data.getBytes());
out.close();
} catch (Exception e) {
e.printStackTrace();
I would prefer to have the file open when the start button is clicked.
if ( v.getId() == R.id.start ){
// checks which button is clicked
Log.d("dennis", "Scan working"); //logs the text
// open a file
try {
FileOutputStream out = openFileOutput("data.csv", Context.MODE_PRIVATE);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
but when it comes to closing the file, no options for .close() appear when out is typed
if ( v.getId() == R.id.stop ){
// checks which button is clicked
out. // no valid options appear
messageValue.setText(R.string.stopButtonText);// changes the hallo world text
readNoRead=false;
}
Does all the open/write/close need to be together or is it possible to
***open file***
-----
Cycle through all the data
-----
***Close file***

You should store a link to your FileOutputStream on top level in your class.
Example to your code:
FileOutputStream out;
void clickStart() {
if (v.getId() == R.id.start){
// checks which button is clicked
Log.d("dennis", "Scan working"); //logs the text
// open a file
try {
out = openFileOutput("data.csv", Context.MODE_PRIVATE);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
void writeData() {
String data= reading1+","+reading2+","+time +"/n";
try {
out.write(data.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
void clickStop() {
if (v.getId() == R.id.stop) {
try {
out.close();
} catch(IOException e) {
e.printStackTrace();
}
messageValue.setText(R.string.stopButtonText);// changes the hello world text
readNoRead=false;
}
}

It is definitely possible to open, process and close a file all in one block without closing the file.
Your out variable is not showing any method suggestions because it has not been defined in that block. Change the line
FileOutputStream out = openFileOutput("data.csv", CONTEXT.MODE_PRIVATE);
to
out = openFileOutput("data.csv", CONTEXT.MODE_PRIVATE);
and then add FileOutputStream out; to a line above the first if statement (outside of the block).
You may want to also look into 'try-catch-finally', or 'try with resources' as options for closing files in a try-catch block.

Related

Android activity won't save information to file

I'm trying to save user information in a single save file in local directory. However every time I run the app, the information doesn't save--I can tell by rerunning the app and the file data isn't updated or returning to the activity and finding out the data displayed isn't updated upon returning to the same activity. Here is the function in the activity where I set up a file output stream and decided to write in the information through a string containing all the User information and display "FILE CLOSED" once I assumed the file has written. Could you spot any missing steps or anything that I missed so that the file can be written?
public void saveToFile() throws FileNotFoundException{
//new filestream
FileOutputStream fostream;
fostream = openFileOutput(fileName, Context.MODE_PRIVATE);
//Write into file for each User in Array
for (int i = 0; i < userArrayList.size(); i++){
String contents = userArrayList.get(i).display();
System.out.println(userArrayList.get(i).display());
try {
fostream.write(contents.getBytes());
} catch (IOException e) {
System.out.println("NOTHING WRITTEN");
e.printStackTrace();
}
}
try {
fostream.close();
System.out.println("FILE CLOSED");
} catch (IOException e) {
e.printStackTrace();
}
}
Thanks so much for your help!

Trying to send data to text file

Hi there I made a program that consist of jtextfield and couple jbuttons. I want to press a jbutton so that the jtextfields will be save to the computer. Any help will be useful.
I think this will help you..
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
if (jTxt_text.getText().isEmpty()) {
JOptionPane.showMessageDialog(rootPane, "Field is empty. Fill the filed and try again.");
} else {
//get the text from the jTextField and save it into a varibale.
String inputText = jTxt_text.getText();
//Where to save the file.
String savePath = "C:/test/sample.txt";
//Creating a file object, file is an abstract representation of file and directory pathnames.
File tempFile = new File(savePath);
//Check wther the file is available or not.
if (!tempFile.exists()) {
try {
//Creates the file if it's not exsising.
tempFile.createNewFile();
} catch (IOException ex) {
ex.printStackTrace();
}
}
try {
//writing process..
FileWriter tempWriter = new FileWriter(tempFile.getAbsoluteFile());
BufferedWriter tempBufferWriter = new BufferedWriter(tempWriter);
tempBufferWriter.write(inputText);
tempBufferWriter.close();
JOptionPane.showMessageDialog(rootPane, "Text file with the written text is successfully saved.");
jTxt_text.setText(null);
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
Still there's a small problem with this code tempBufferWriter.write(inputText) returns void so.. i don't know how to check wther the process completed successfully from the code itself..

Save file with FileOutputStream does not create any file

Currently I'm developing an android app where the user has to click on a button this adds +1 to a count. After 100 there is another button which causes a reset of the count and increase the level and difficulty which is stored in another 2 "ints". Well its all working but I seriously have big problems with creating a save file.
-I gave me the permission via AndroidManifest.xml
-Tryed 3 other code examples
I did import everything that is necessary and the rest of the code is working
There has to be a mistake in this part of my code:
(my part for the Saving the "Stats")
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
FileOutputStream savelvl = openFileOutput("savelvl.data", Context.MODE_PRIVATE);
savelvl.write(level);
savelvl.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
can anyone suggest an improvement to the code or tell me the mistake in saving the file to the internal storage?
I've had success with using a BufferedWriter instead of FileOutputStream, although I'm sure it could given a different setup. Below is some code with "FileOutputStream out", which I was trying to use initially, commented out.
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter(file,true));
//out = new FileOutputStream(file);
Log.i("file","file opened");
writer.write(someString);
//out.write(someString.getBytes());
Log.i("file","file written");
} catch (Exception e) {
Log.e("fileNotFound","file not found exception");
e.printStackTrace();
}/*
try {
out.write(someString.getBytes());
Log.i("file","file written");
Log.i("str2File",someString.getBytes().toString());
} catch (IOException e) {
Log.e("fileWrite","file write error");
e.printStackTrace();
}*/ finally {
try {
//out.getFD().sync();
//out.close();
writer.close();
Log.i("file","file closed");
} catch (Exception e) {
Log.e("closeError","error closing file");
e.printStackTrace();
}
}
You cannot flush your data. When you use writer you must call flush method after write method.
OutputStrem stream = ... // I cannot create new reference because "OutStream" class is abstract
stream.write(data, offset, length);
stream.flush();
stream.close();

Android FileObserver onEvent not getting called

Can someone possibly help me with this?
I want to observe a file to see if it gets modified so that I can update the activity. After several tests, I've determined it's just plain not working.
Am I doing something wrong?
I'm creating a FileObserver with an onEvent method to display a Toast and log data just to see if it's working, however the onEvent is never getting called.
I have tried it both with an existing and a new file, but it doesn't seem to work in either case.
Context context = this;
File fileFolder = context.getFilesDir();
String fileName = "quest";
FileObserver questObserver = new FileObserver(fileFolder.getPath()) { // also tried fileFolder.getName()
#Override
public void onEvent(int event, String path) {
Toast.makeText(getApplicationContext(), "onEvent fired", Toast.LENGTH_LONG).show();
Log.d(TAG, "FileObserver().onEvent");
}
};
questObserver.startWatching();
/* create file */
ObjectOutputStream objectOut = null;
try {
FileOutputStream fileOut = context.openFileOutput(fileName, Context.MODE_PRIVATE);
objectOut = new ObjectOutputStream(fileOut);
objectOut.writeObject(new Quest());
fileOut.getFD().sync();
} catch (IOException e) {
Log.d(TAG, e.getMessage());
} finally {
if (objectOut != null) {
try {
objectOut.close();
} catch (IOException e) {
Log.d(TAG, e.getMessage());
}
}
}
/* read file */
ObjectInputStream objectIn = null;
Quest quest = null;
try {
FileInputStream fileIn = context.openFileInput(fileName);
objectIn = new ObjectInputStream(fileIn);
quest = (Quest) objectIn.readObject();
} catch (FileNotFoundException e) {
// Do nothing
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
if (objectIn != null) {
try {
objectIn.close();
} catch (IOException e) {
Log.d(TAG, e.getMessage());
}
}
}
Toast.makeText(context, quest.getTitle(), Toast.LENGTH_LONG).show();
questObserver.stopWatching();
Any help would be greatly appreciated.
'public abstract void onEvent (int event, String path)" -
This method is invoked on a special FileObserver thread. It runs
independently of any threads, so take care to use appropriate
synchronization! Consider using post(Runnable) to shift event handling
work to the main thread to avoid concurrency problems.
http://developer.android.com/reference/android/os/FileObserver.html
If you put the toast through a handler.post(new Runnable(){...}), that should work.
Assuming your file doesn't (always) exist you should probably put your observer on the files folder, obtained like so:
Context ctx = ...;
File filesFolder = ctx.getFilesDir();
Note that this will also ensure that the filesFolder directory will be created.
Your observer will now be notified whenever a file is written, deleted or updated using for instance Context#.openFileOutput(..) - and you can filter in your FileObserver for the file name, in your example "quest".

FileOuputStream Write bytes for loop, but no data write?

Listing my program fragment as below
public class InStream {
static FileOutputStream file=null;
static {
try {
file = new FileOutputStream("deo.txt");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
try {
//when i try to replace below infinite loop,
//it is also not able to output my String
//while(ture)
or
//for(;;)
for(int i=0;i<100000;i++){
file.write("AB ".getBytes());
}
//file.flush();
file.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Run this program -> open deo.txt -> there are no data within this file
but when i comment the for loop just only test below fragment code:
try {
file.write("AB ".getBytes());
file.close();
} catch (Exception e) {
e.printStackTrace();
}
Now i can see the "AB " string in the file. so strange....
Can any one do me a favor?
There is no error in your code. File "deo.txt" must be generate which contains AB AB...............
I tested your code. And it works. But for the deo.txt. You can check its size if it is about 293k. It displays nothing if you open it with Eclipse text editor. But you can view it with other system editor, such as notepad++.

Categories