Reading a text file line by line in android [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
hi i just started learning android development and i'm trying to build an app that reads text from files.
i have been searching all over the internet but i don't seem to find the way to do so , so i have a few questions..
1.how to do this?
what is the preferred way to read a file line by line in android?
2.where should i store the file?
should it be in the raw folder or maybe in the assets folder?
so this is what i already tried: " (i think the problem may be with finding the file..)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.filereader);
try {
// open the file for reading
InputStream fis = new FileInputStream("text.txt");
// if file the available for reading
if (fis != null) {
// prepare the file for reading
InputStreamReader chapterReader = new InputStreamReader(fis);
BufferedReader buffreader = new BufferedReader(chapterReader);
String line;
// read every line of the file into the line-variable, on line at the time
do {
line = buffreader.readLine();
// do something with the line
System.out.println(line);
} while (line != null);
}
} catch (Exception e) {
// print stack trace.
} finally {
// close the file.
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

Depends on what you intend to do with that file. If your goal is only to read the file, then the asset folder is the way to go. If you want to store information in that file when you are done working with it, you should put it on the device.
If you choose option number 2, you need to decide if you want other applications to read the file. More information can be found at this address:
http://developer.android.com/training/basics/data-storage/files.html
Else, you can read/write directly to the device with the standard java procedure just like you described. Though, the filepath would probably be
"/sdcard/text.txt"
EDIT:
Here's some piece of code to get started with
FileInputStream is;
BufferedReader reader;
final File file = new File("/sdcard/text.txt");
if (file.exists()) {
is = new FileInputStream(file);
reader = new BufferedReader(new InputStreamReader(is));
String line = reader.readLine();
while(line != null){
Log.d("StackOverflow", line);
line = reader.readLine();
}
}
But it assumes that you know you've put the text.txt at the root of your sdcard.
If the file is in the assets folder, you have to do this:
BufferedReader reader;
try{
final InputStream file = getAssets().open("text.txt");
reader = new BufferedReader(new InputStreamReader(file));
String line = reader.readLine();
while(line != null){
Log.d("StackOverflow", line);
line = reader.readLine();
}
} catch(IOException ioe){
ioe.printStackTrace();
}

Your code looks good however, you should do your file reading asynchronously.
For the file path, it depends if it is a file that you bundle in your APK or a file that you download in the app data folder.
Depending on what version of android you are targeting, I would use try with resources...
to read from assets you can do this in an activity:
reader = new BufferedReader(
new InputStreamReader(getAssets().open("filename.txt")));

Related

FileNotFound exception but there is a file (Java Eclipse)

I cant get rid of this FileNotFound error even though the file exists. Any ideas? (There are hundreds of lines of code so im just going to paste the chunk around the error, if this is an issue I can post more)
// method start
System.out.println(System.getProperty("user.dir"));
File names = new File("src/guiProject/nameList");
System.out.println(names.getAbsolutePath());
// !!!! V ERROR OCCURS HERE V !!!!
BufferedReader br = new BufferedReader(new FileReader(names));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
line = br.readLine();
}
String allNames = sb.toString();
userListArea.setText(allNames);
} catch (IOException o) {
o.printStackTrace();
} finally {
try {
br.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
//method end
Probably your Windows does not show file extensions; nameList.txt?
Otherwise the working directory is not in the project directory with subdirectory src.
A FileReader uses the default Charset, so the file is not portable. If you run the application on another platform then the developer's, the encoding is wrong.
Best use UTF-8, full Unicode.
Then the reading strips the line ending:
while (line != null) {
sb.append(line).append("\r\n");
line = br.readLine();
}
You could do:
Path names = Paths.get("src/guiProject/nameList.txt"); // File
Path names = Paths.get(
MyClass.class.getResource("/guiProject/nameList.txt").toURI()); // Resource
String allNames = new String(Files.readAllBytes(names), StandardCharsets.UTF_8);
userListArea.setText(allNames);
If it is a read-only file, stored in the application jar, it is a resource rather than a disk File.
Maybe you are not in the folder you think.
Create a file with a dummy name and get the absolute path of this file, this way you can doublecheck you are where you think you really are.

jTextArea saves only first line of text in text file using BufferedReader?

I am trying to save the multiple line output in a text file from my jTextArea(named as "outputarea" in a code) to my desired path, Everything is OK but the file being saved do not contain the whole output, but only first line oof text. I am using "\n" to break the line in jtextarea while giving multiple line output, does that make any difference or any other problem in this code, This code is just the code on saveAs button, output is coming from another methods I've created. Thanks in Advance!
private void saveAs() {
FileDialog fd = new FileDialog(home.this, "Save", FileDialog.SAVE);
fd.show();
if(fd.getFile()!=null)
{
fn=fd.getFile();
dir=fd.getDirectory();
filename = dir + fn +".txt";
setTitle(filename);
try
{
DataOutputStream d=new DataOutputStream(new FileOutputStream(filename));
holdText = outputarea.getText();
BufferedReader br = new BufferedReader(new StringReader(holdText));
while((holdText = br.readLine())!=null)
{
d.writeBytes(holdText+"\r\n");
d.close();
}
}
catch (Exception e)
{
System.out.println("File not found");
}
outputarea.requestFocus();
save(filename);
}
}
You should put the d.close(); after the completion of while loop, because just after writing the first line in the file using DataOutputStream, you are closing it and you don't let it to fulfill the whole job.
You can see even an error is wrote in your console:
File not found
This is not because it doesn't find your file, it's because in the iterations after the first, it tries to write into a closed stream. So only the first line is wrote then. So change you code like this:
while ((holdText = br.readLine()) != null) {
d.writeBytes(holdText + "\r\n");
}
d.close();
Also I can advise to use a PrintWriter instead of DataOutputStream. Then you can easily change the writeBytes into println method. In this way you don't need to append \r\n manually to each line you write.
Another good hint is to use a try-with-resource (in case you use java 7 or later) or at least a finally block to close your streams either way:
String holdText = outputarea.getText();
try (PrintWriter w = new PrintWriter(new File(filename));
BufferedReader br = new BufferedReader(new StringReader(holdText))) {
while ((holdText = br.readLine()) != null) {
w.println(holdText);
}
} catch (Exception e) {
System.out.println("File not found");
}
Good Luck.

write & read textfiles on external micro-sd card with project tango developer tablet

I want to read and write textfiles on the external micro-sd card from my project tango developer tablet.
This is my code for reading (it works):
/* Checks if external storage is available for read and write */
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
String secondaryStore = System.getenv("SECONDARY_STORAGE") + "/Testordner";
Log.d("secondaryStore", "" + secondaryStore);
File file = new File(secondaryStore, "file.txt");
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
br.close();
} catch (Exception e) {
Log.d("Exception", "");
}
Log.d("Text", "" + text.toString());
}
And this is my code for writing (it doesn't work yet):
try {
File file2 = new File(secondaryStore,"file2.txt");
FileWriter writer = new FileWriter(file2);
writer.append("Hello World!");
writer.flush();
writer.close();
} catch (Exception e) {
Log.d("Exception", "");
}
What am I doing wrong? Or is there still an error with the tango tablet? I found these two links, but trying to fix the problem with these two apps don't work:
https://github.com/chucknology/TangoSDfix
https://github.com/chucknology/TangoRoot
I had the same problem, when creating new files. The file is actually created but android filesystem is not updated with the new file (you can actually see it if you restart your tablet).
Adding this line after closing my file actually helped android filesystem to notice my file right away.
MediaScannerConnection.scanFile(mActivity, new String[]{file.toString()}, null, null);
Hope that it works for you.

Why does introducing a FileWriter delete all the content in the file?

I have a text file with some text in it and i'm planning on replacing certain characters in the text file. So for this i have to read the file using a buffered reader which wraps a file reader.
File file = new File("new.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String line = null;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
But since i have to edit characters i have to introduce a file writer and add the code which has a string method called replace all. so the overall code will look as given below.
File file = new File("new.txt");
FileWriter fw = new FileWriter(file);
BufferedReader br = new BufferedReader(new FileReader(file));
String line = null;
while ((line = br.readLine()) != null) {
System.out.println(line);
fw.write(br.readLine().replaceAll("t", "1") + "\n");
}
Problem is when i introduce a file writer to the code (By just having the initialization part and when i run the program it deletes the content in the file regardless of adding the following line)
fw.write(br.readLine().replaceAll("t", "1") + "\n");
Why is this occurring? am i following the correct approach to edit characters in a text file?
Or is there any other way of doing this?
Thank you.
public FileWriter(String fileName,
boolean append)
Parameters:
fileName - String The system-dependent filename.
append - boolean if true, then data will be written to the end of the
file rather than the beginning.
To append data use
new FileWriter(file, true);
The problem is that you're trying to write to the file while you're reading from it. A better solution would be to create a second file, put the transformed data into it, then replace the first file with it when you're done. Or if you don't want to do that, read all of the data out of the file first, then open it for writing and write the transformed data.
Also, have you considered using a text-processing language solution such as awk, sed or perl: https://unix.stackexchange.com/questions/112023/how-can-i-replace-a-string-in-a-files
You need to read the file first, and then, only after you read the entire file, you can write to it.
Or you open a different file for writing and then afterwards you replace the old file with the new one.
The reason is that once you start writing to a file, it is truncated (the data that was in the file is deleted).
The only way to avoid that is to open the file in "append" mode. With that mode, you start writing at the end of the file, so you don't delete its content. However, you won't be able to modify the existing content, you will only add content.
Maybe like this
public static void main(String[] args) throws IOException {
try {
File file = new File("/Users/alexanderkrum/IdeaProjects/printerTest/src/atmDep.txt");
Scanner myReader = new Scanner(file);
ArrayList<Integer> numbers = new ArrayList<>();
while (myReader.hasNextLine()) {
numbers.add(myReader.nextInt() + 1);
}
myReader.close();
FileWriter myWriter = new FileWriter(file);
for (Integer number :
numbers) {
myWriter.write(number.toString() + '\n');
}
myWriter.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
Just add at last :
fw.close();
this will close it ,then it will not delete anything in the file.
:)

JAVA What am I doing wrong, I want the line [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I am trying to make a change log and so I need a single line between some sentences.
All I have is this but it doesn't seem to work. Can anyone help me please?
#Test
public void addLine() {
File temp;
try {
temp = File.createTempFile("app.log", ".tmp", new File("."));
File appLog = new File("app.log");
try (BufferedWriter bw = new BufferedWriter(new FileWriter(temp));
BufferedReader br = new BufferedReader(new FileReader(
appLog))) {
String line;
while ((line = br.readLine()) != null) {
bw.write(line);
bw.newLine();
if ("2 A".equals(line)) {
bw.write("New Line!");
bw.newLine();
}
}
appLog.delete();
temp.renameTo(appLog);
}
} catch (IOException e) {
e.printStackTrace();
}
}
The problem that you might be encountering might be because of the "line separator" used by the BufferedWriter (it gets set when you create said class). I think it would be best to use instead:
System.getProperty("line.separator");
This way you use the System's line separator rather than a hard coded one.
So that your code would look like this:
public void addLine() {
String lineseparator=System.getProperty("line.separator");
// I'd suggest putting this as a class variable, so that it only gets called once rather
// than
// everytime you call the addLine() method
try {
FileWriter stream = new FileWriter(this.log, true);
//If you don't add true as the second parameter, then your file gets rewritten
// instead of appended to
BufferedWriter out = new BufferedWriter(stream);
out.write(lineseparator); //This substitutes your out.newline(); call
out.close();
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
##############################################################################.
I will try to be as brief and clear as possible.
I assume that you are opening a file that in my code I call "test.txt" and it's got about a paragraph or so. And that you want that outputted to another file, but with "empty lines" at some points.
Because File() is read line by line, it is much easier to open your main file read a line, and then write it to your log file, then analyse if an empty line is necessary and place it.
Let's see some code then.
// Assume you have a private class variable called
private String lineseparator=System.getProperty("line.separator");
// This method is in charge of calling the method that actually carries out the
// reading and writing. I separate them both because I find it is much cleaner
// to have the try{}catch{} blocks in different methods. Though sometimes for
// logging purposes this is not the best choice
public void addLines() {
try {
readAndWrite();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
// This method is in charge of reading one file and output to another.
public void readAndWrite() throws IOException {
File test = new File("test.txt");
FileWriter writer = writer = new FileWriter(new File("log.txt"), true);
//This FileWriter is in charge of writing to your log file
String line;
boolean conditionToWriteNewLine=true;
//Obviously this needs to be changed to suit your situation
// I just added it for show
BufferedReader reader = new BufferedReader( new FileReader (test));
BufferedWriter out = new BufferedWriter(writer);
//It is in this while loop that you read a line
// Analyze whether it needs to have a new line or not
// and then write it out to log file
while( ( line = reader.readLine() ) != null ) {
out.write(line);
if(conditionToWriteNewLine){
out.write(this.lineseparator);
out.write(this.lineseparator);
//You need to write it twice for an EMPTY LINE
}
}
reader.close();
out.close();
}
One of the big differences from this code is that I only open the files once, while in your code you open the log file every time you want to add a new file. You should read the documentation, so you'll know that every time you open the file, your cursor is pointing to the first line, so anything you add will be added to first line.
I hope this helped you understand some more.
I'm not totally sure what you are asking for, but have you tried setting the "append" flag on true, so the FileWriter will not start a new file, but append content to it at the end? This is done by calling the FileWriter(File, boolean) constructor:
public void addLine() {
try {
FileWriter stream = new FileWriter(this.log, true); // Here!
BufferedWriter out = new BufferedWriter(stream);
out.write("New Extra Line Here");
out.newLine();
out.close();
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
I need a single line between some sentences
I guess you mean a new line between other lines of the same file.
To do so you have to read the whole file, locate the place where you want to insert a line, insert the line then write the new content to the file.
This should work fine for small files but if you have large files you might get in trouble.
So you need a more scaleable way of doing it: Read line by line, and write write to a temp file. if you indentify the location where a new line should be inserted, write that line. Continue with the rest of the file. After you are done delete the original file and rename the temp file with the original name.
Pseudocode:
Open actual file
Open temp file
while not end of actual file
Read one line from actual file
Check if new line has to inserted now
Yes: write new line to temp
write line from actual to temp
Close actual file
Close temp file
Delete actual
Rename temp to actual
Code example: (unlike the pseudo code, the new line is inserted after)
Here the line "New Line!" is inserted after each line which is equal to "2 A".
#Test
public void insertNewLineIntoFile() throws IOException {
File temp = File.createTempFile("app.log", ".tmp", new File("."));
File appLog = new File("app.log");
try (BufferedWriter bw = new BufferedWriter(new FileWriter(temp));
BufferedReader br = new BufferedReader(new FileReader(appLog))) {
String line;
while((line = br.readLine()) != null) {
bw.write(line);
bw.newLine();
if("2 A".equals(line)) {
bw.write("New Line!");
bw.newLine();
}
}
appLog.delete();
temp.renameTo(appLog);
}
}
Note that File#delete() and File#renameTo both return a boolean value that is true onyl if the operation was successfull. You absolutely need to check those retuned values and handle accordingly.
out.println("\n");
(instead of out.newLine();)
\n in java declares a new line. If you dont add any text before it then it should just print a blank line like you want.
This will work Correctly.
Suggestion:
out.close(); and stream.close(); should write inside finally block ie they should close even if some exceptions occured.

Categories