Reading an internal file in Android Studio - java

I am writing to an internal file in Android Studio
String filename = "output.txt";
String fileContents = studentNum + ", " + lastName + ", " + firstName + ", " + radioValue + ", " + spinnerInfo + "\n"; // edit this to include all content
FileOutputStream outputStream;
try{
outputStream = openFileOutput(filename, Context.MODE_APPEND);
outputStream.write(fileContents.getBytes());
outputStream.close();
} catch(Exception e){
e.printStackTrace();
}
}
The code lets me write lines of data split with commas. I am able to then go to another activity and read it all out at once.
String file = "output.txt";
String line = "";
String data = "";
//File read operation
try {
FileInputStream fis = openFileInput(file); //A FileInputStream obtains input bytes from a file in a file system
InputStreamReader isr = new InputStreamReader(fis); //An InputStreamReader is a bridge from byte streams to character streams
BufferedReader br = new BufferedReader(isr); //Reads text from a character-input stream,
while ((line = br.readLine()) != null) {
data += (counter+1) + "\t"+ line +"\n";
counter++;
}
}catch (FileNotFoundException e){
e.printStackTrace();
}
catch (IOException e){
e.printStackTrace();
}
//Show the data
txtOutput.setText(data);
However I want to be able to read only one line of data per activity and when I click a button it transfers down to the next line of data. And goes in a carousel loop so once we reach the last line it will go to the first line of data once the button is clicked again

The easiest thing is probably just to keep a line number pointer (since you are reading by line), and read down that many lines to get where you want at each activity. If the file is large or you are otherwise performance conscious this is not a great option.
Both InputStream and Reader have a skip(<bytes>) method. You could also do it that way. Obviously if you use a stream you need to read by bytes not by line, so a little more trouble.
You could also use a RandomAccessFile that has a seek() method. Again this is accessed by byte index.

Related

Reading a .txt file using BufferedReader and FileReader

I used BufferedReader and FileReader to read a file but everytime I read it, it just displays no name found. Thanks in advance.
BufferedReader ifile = new BufferedReader (new FileReader ("data.txt"));
String N;
while(true)
{
N=ifile.readLine();
if (N == null){
System.out.print("\fNo name found\n");
break;
}
number = Integer.parseInt(ifile.readLine());
house = ifile.readLine();
form = ifile.readLine();
dob = ifile.readLine();
System.out.println("Name: " + N + "\nNumber: " + number + "\nHouse: " + house + "\nForm: " + form + "\nDate of Birth: " + dob);
}
ifile.close();
Answer might have already been given in another topic like: Read all lines with BufferedReader
So it might be a duplicate.
However when you read a file via BufferedReader it is recommended you do it like
FileReader filereader = new FileReader("data.txt");
BufferedReader ifile = new BufferedReader(filereader);
String N;
ArrayList<String> file_contents= new ArrayList<String>();
//List will now contain the whole txt
try {
while((N = input.readLine()) != null) {
file_contents.add(N);
}
ifile.close();
}
catch(IOException e){
e.printStackTrace();
}
And then break the list's contents to get what you want.
Using a try/catch block can avoid the error of not knowing how to handle that the file "data.txt" cannot be read.
Your way of doing it (while(true)) doesn't pass the name in any variable so it can be printed out and also just checks if the 1st line of your data.txt file is empty or not and does nothing with the remaining lines if that condition is true.
In addition to the above check if the source of your problem is in the txt file.
For example if its structure is the way you want it to be.

How to add a new line after writing a array of characters into a file using JAVA

After executing the following piece of code
String content = new String("CONSOLIDATED_UNPAID_code_" + code2 + "_" + countryCode2 + " = " + reason2);
try {
fileOutputStream.write(content.getBytes());
}
catch (IOException e) {
e.printStackTrace();
}
output is as follows:.
CONSOLIDATED_UNPAID_code_64 _KE = Account Dormant-Refer to DrawerCONSOLIDATED_UNPAID_code_65 _KE = Wrong/Missing Account Number (EFT)CONSOLIDATED_UNPAID_code_66 _KE = Wrong/Missing Reference
but i want it like
CONSOLIDATED_UNPAID_code_64 _KE = Account Dormant-Refer to Drawer
CONSOLIDATED_UNPAID_code_65 _KE = Wrong/Missing Account Number (EFT)
Pls suggest
I'd have to see the rest of the code to tell you exactly what you should do, but you can simply use the character "\n" in your string.
You can achieve adding new line to a file in quite a few ways, here is the two approaches:
Add a \n to your String which would cause the remainder of the string to be printed in new line
Use PrintWriter's println method to print each string in new line
Also keep in mind that opening a file with Notepad might not recognize \n hence do not display the remainder of string in new line, try opening the file using Notepadd++
String code2 = "code12";
String countryCode2 = "countryCode2";
String reason2 = " \n I am reason.";
String content = new String("CONSOLIDATED_UNPAID_code_" + code2 + "_" + countryCode2 + " = " + reason2);
try {
fout.write(content.getBytes());
//don't forget to flush the output stream
fout.flush();
} catch (IOException e) {
e.printStackTrace();
}
Use PrintWriter as shown below:
String line1 = "This is line 1.";
String line2 = "This is line 2.";
File f = new File("C:\\test_stackoverflow\\test2.txt");
PrintWriter out = new PrintWriter(f);
out.println(line1);
out.println(line2);
//close the output stream
out.close();
First, use a Writer on top of the output stream to write strings to files. This way, you'll be in control of the output character encoding.
Second, if you want to use your platform's line separator, you may use PrintWriter which has println() methods using the correct newline character or character sequence.
PrintWriter writer = new PrintWriter(
new OutputStreamWriter(fileOutputStream, OUTPUT_ENCODING)
);
...
writer.println(content);
Found solution for this . Appending /n wouldnt solve any issue rather use BufferedWriter. BufferedWriter has a inbuilt newline mwthod to do the same. Thanks
Solution:
try {
File file = new File("Danny.txt");
FileOutputStream fileOutputStream = new FileOutputStream(file);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fileOutputStream) );
String content = new String("CONSOLIDATED_UNPAID_description_"+code2+"_"+countryCode2+" = "+description2);
bw.write(content);
bw.newLine();
bw.flush();
check = true;
}
catch (IOException e) {
e.printStackTrace();
}

Updating a single line on a text file with a Java method

I know previous questions LIKE this one have been asked, but this question has to do with the specifics of the code that I have written. I am trying to update a single line of code on a file that will be permanently updated even when the program terminates so that the data can be brought up again. The method that I am writing currently looks like this (no compile errors found with eclipse)
public static void editLine(String fileName, String name, int element,
String content) throws IOException {
try {
// Open the file specified in the fileName parameter.
FileInputStream fStream = new FileInputStream(fileName);
BufferedReader br = new BufferedReader(new InputStreamReader(
fStream));
String strLine;
StringBuilder fileContent = new StringBuilder();
// Read line by line.
while ((strLine = br.readLine()) != null) {
String tokens[] = strLine.split(" ");
if (tokens.length > 0) {
if (tokens[0].equals(name)) {
tokens[element] = content;
String newLine = tokens[0] + " " + tokens[1] + " "
+ tokens[2];
fileContent.append(newLine);
fileContent.append("\n");
} else {
fileContent.append(strLine);
fileContent.append("\n");
}
}
/*
* File Content now has updated content to be used to override
* content of the text file
*/
FileWriter fStreamWrite = new FileWriter(fileName);
BufferedWriter out = new BufferedWriter(fStreamWrite);
out.write(fileContent.toString());
out.close();
// Close InputStream.
br.close();
}
} catch (IOException e) {
System.out.println("COULD NOT UPDATE FILE!");
System.exit(0);
}
}
If you could look at the code and let me know what you would suggest, that would be wonderful, because currently I am only getting my catch message.
Okay. First off the bat, StringBuilder fileContent = new StringBuilder(); is bad practice as this file could well be larger than the user's available memory. You should not keep much of the file in memory at all. Do this by reading into a buffer, processing the buffer (adjusting it if necessary), and writing the buffer to a new file. When done, delete the old file and rename the secondary to the old one's name. Hope this helps.

Appending to text file then displaying only certain fields

I'm making a savings calculator using netbeans with a JFrameForm. below is my working code to save to a .txt. for some reason when I click save it will not append to a new line and wont save at all. I would like to then load certain rows to an array and display in my text area. eg the savings field. First code for the save button, second block for the load button.
BufferedWriter writer = null;
try{
writer = new BufferedWriter(new FileWriter("C:\\test.txt"));
writer.write("\n" + date + "\t" + gross + "\t" + tax + "\t" + savings);
}
catch (Exception e){
JOptionPane.showMessageDialog(null, "Error saving");
}finally{
try{
//close the writer
writer.close();
}catch (Exception e){
JOptionPane.showMessageDialog(null, "Error closing save");
}
}
try{
FileReader reader = new FileReader("C:\\test.txt");
BufferedReader br = new BufferedReader(reader);
txaMain.read(br, null);
br.close();
}
catch(Exception E){
JOptionPane.showMessageDialog(null, "Error opening file");
}
for some reason when I click save it will not append to a new line and wont save at all
It is not saving because you are not flushing the character buffer stream that was grab from your write method.
solution:
flush it after you write from the text file
writer = new BufferedWriter(new FileWriter("C:\\test.txt"));
writer.write("\n" + date + "\t" + gross + "\t" + tax + "\t" + savings);
writer.flush();
Also if you want to append to the file while saving the text then add one more parameter in your FileWriter FileWriter("C:\\test.txt, true") true means to append the file when writing.
public FileWriter(String fileName,
boolean append)

Saving String Input on Android

Right, I've been trying to find a solution to this for a good while, but it's just not working for some reason.
In short, what I want to do is save every input String the user inputs into a file. Every time the activity is created again, I want to re-input these strings into a new instance of an object.
This code is what I use to create the file and read info from it, used in the onCreate() method of activity
try {
String brain = "brain";
File file = new File(this.getFilesDir(), brain);
if (!file.exists()) {
file.createNewFile();
}
BufferedReader in = new BufferedReader(new FileReader(file));
String s; // This feeds the object MegaAndroid with the strings, sequentially
while ((s = in.readLine()) != null) {
MegaAndroid.add(s);
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
After that, every time the user inputs some text, the strings are saved onto the file:
try {
String brain = "brain";
File file = new File(this.getFilesDir(), brain);
if (!file.exists()) {
file.createNewFile();
}
BufferedWriter out = new BufferedWriter(new FileWriter(file));
out.write(message); // message is a string that holds the user input
out.close();
} catch (IOException e) {
e.printStackTrace();
}
For some reason, however, every time the application is killed, the data is lost.
What am I doing wrong?
EDIT: Also, if I were to access this file from another class, how can I?
As we discussed in the commend section the chief problem with the code is that your execution of FileWriter occurred prior to your FileReader operation while truncating the file. For you to maintain the file contents you want to set the write operation to an append:
BufferedWriter out = new BufferedWriter(new FileWriter(file,true));
out.write(message);
out.newLine();
out.close();
However, if every entry on the EditText is received then shipped into the file you'll just be writing data byte after byte beside it. It is easy to get contents similar to
This is line #1This is line #2
Instead of the desired
This is line #1
This is line #2
which would be corrected by having the BufferedWriter pass a newline after each write to the file.
This is what I do for file reading.
try{
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath() + "/whereyouwantfile");
dir.mkdirs();
Log.d(TAG,"path: "+dir.getAbsolutePath());
File file = new File(dir, "VERSION_FILENAME");
FileInputStream f = new FileInputStream(file);
//FileInputStream fis = context.openFileInput(VERSION_FILENAME);
BufferedReader reader = new BufferedReader(new InputStreamReader(f));
String line = reader.readLine();
Log.d(TAG,"first line versions: "+line);
while(line != null){
Log.d(TAG,"line: "+line);
//Process line how you need
line = reader.readLine();
}
reader.close();
f.close();
}
catch(Exception e){
Log.e(TAG,"Error retrieving cached data.");
}
And the following for writing
try{
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath() + "/whereyouwantfile");
dir.mkdirs();
File file = new File(dir, "CONTENT_FILENAME");
FileOutputStream f = new FileOutputStream(file);
//FileOutputStream fos = context.openFileOutput(CONTENT_FILENAME, Context.MODE_PRIVATE);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(f));
Set<String> keys = Content.keySet();
for(String key : keys){
String data = Content.get(key);
Log.d(TAG,"Writing: "+key+","+data);
writer.write(data);
writer.newLine();
}
writer.close();
f.close();
}
catch(Exception e){
e.printStackTrace();
Log.e(TAG,"Error writing cached data.");
}
You can use the private mode if you don't want the rest of the world to be able to see your files, but it is often useful to see them when debugging.

Categories