I have a text file placed in assets and I want to read one line of it at a time. My problem is that I do not know how to access the file in Activity, and then once I access it, how would I go about only selecting one line?
If keeping the txt file in assets is a bad idea, where should I put it for easier access?
I really appreciate any help!
This is a snippet I use to prepopulate tables in my RSS feed reader. You can use it as a track for your needs.
In res/raw/ I have file feeds.txt. The file is referenced is code like R.raw.feeds.
final Resources resources = mHelperContext.getResources();
InputStream inputStream = resources.openRawResource(R.raw.feeds);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream), 8192);
try {
String line;
while ((line = reader.readLine()) != null) {
//make the use you want with "line"
}
} catch (IOException e) {
Log.e(TAG, "Error loading sample feeds.");
throw new RuntimeException(e);
}
To open assests, you'll need to call
<context>.getAssets().open(<your file>);
<context> is your activity, so if this is in your onCreate, then it would be this. That call returns an inputstream, which you can then handle however you please.
I don't see how it would be a particularly bad idea to keep your text file there, depends on what you're using that text file for.
Try this:
Make a new method for example readMyFile().
It must looks like this:
private String readMyFile(File file) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(file));
StringBuilder txt = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
txt.append(line);
txt.append("\n");
}
reader.close();
return txt.toString();
Paste it to your code, and use the method (readMyFile([the file what you want to read in assets]).
Hope it helps.
Related
I am analyzing a web access log and try to find out all the unique object (any file or any path) that were requested only once in the access log. Every time the program write into the text file, the content of the text file looks like this :
/~scottp/publish.html
/~ladd/ostriches.html
/~scottp/publish.html
/~lowey/
/~lowey/kevin.gif
/~friesend/tolkien/rootpage.html
/~scottp/free.html
/~friesend/tolkien/rootpage.html
.
.
.
I want to check if the line which is going to write into the text file is already exist in the text file. In order words, if it's does exist in the text file, then do nothing and skip it and analyze the next line. If not, then write it into the text file.
I tried to use equals or contains but it doesn't seems to be work, here's a little pieces of my code:
// Find Unique Object that were requested only once
if (matcher3.find()) {
if(!requestFileName.equals(bw.equals(requestFileName))) {
bw.write(requestFileName);
bw.newLine();
}
}
What should I do to actually perform a check ?
As #JB Nizet commented you should make use of Set
Set<String> set = new HashSet<String>();
BufferedReader reader = new BufferedReader(new FileReader(new File("/path/to/yourFile.txt")));
String line;
while((line = reader.readLine()) != null) {
// duplicate
if(set.contains(line))
continue;
set.add(line);
// do your work here
}
Perhaps something simple like this:
try (BufferedReader br = new BufferedReader(new FileReader(yourFilePath))) {
boolean lineExists = false;
String currentLine;
while ((currentLine = br.readLine()) != null) {
if (currentLine.trim().equalsIgnoreCase(requestFileName.trim())) {
lineExists = true;
break;
}
}
br.close();
if (!lineExists) {
bw.write(requestFileName);
bw.newLine();
}
}
catch (IOException e) {
// Do what you want with Exception...
}
I wanted to know if there is any method in java to access the contents of the file in the computer.
For example if I want to make a word guessing game in which I want to access the words kept in a file randomly.
(I heard of something called "FileReader" but can't understand how to use it.)
Hope you understand what I mean.
Thanks!!
You can also read an entire text file as a List with Files.readAllLines . You can do it like this (read and print):
List<String> sl= Files.readAllLines(Paths.get("test1.txt"));
for (String s:sl) {
System.out.println(s);
}
Another option is to use Files.newBufferedReader like this:
try (BufferedReader br= Files.newBufferedReader(Paths.get("test1.txt")))
{
String line;
while ((line=br.readLine())!=null) System.out.println(line);
}
The try(){ } construct is called try-with-resorces, it closes the open file object (br in this case) automatically when finished. It is vital for writing, and is a good coding practice for reading.
You can read contents of File like this.
public void readFile(String fileName){ //Pass file's absolute path
BufferedReader reader = new BufferedReader(new FileReader(fileName));
String line = null;
while((line=reader.readLine())!=null){
System.out.println(line);
}
}
When I read a file from the jar file and want to put it in in a jTextArea, it shows me crypted symbols, not the true content.
What I am doing:
public File loadReadme() {
URL url = Main.class.getResource("/readme.txt");
File file = null;
try {
JarURLConnection connection = (JarURLConnection) url
.openConnection();
file = new File(connection.getJarFileURL().toURI());
if (file.exists()) {
this.readme = file;
System.out.println("all ok!");
}
} catch (Exception e) {
System.out.println("not ok");
}
return file;
}
And then i read the file:
public ArrayList<String> readFileToArray(File file) {
ArrayList<String> array = new ArrayList<String>();
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader(file));
while ((sCurrentLine = br.readLine()) != null) {
String test = sCurrentLine;
array.add(test);
}
} catch (IOException e) {
System.out.println("not diese!");
} finally {
try {
if (br != null)
br.close();
} catch (IOException ex) {
}
}
return array;
}
Now, i put all lines from the ArrayList in the jTextArea, that showes me things like that:
PK����?����^��S?��3��� z_��
%�Q Tl?7��+�;�
�fK� �N��:k�����]�Xk,������U"�����q��\����%�Q#4x�|[���o� S{��:�aG�*s g�'.}���n�X����5��q���hpu�H���W�9���h2��Q����#���#7(�#����F!��~��?����j�?\xA�/�Rr.�v�l�PK�bv�=
The textfiled contains:
SELECTION:
----------
By clicking the CTRL Key and the left mouse button you go in the selection mode.
Now, by moving the mouse, you paint a rectangle on the map.
DOWNLOAD:
---------
By clicking on the download button, you start the download.
The default location for the tiles to download is: <your home>
I am sure that the file exists!
Does anyone know what the problem is? Is my "getResource" correct?
Based on the output, I'm suspecting your code actually reads the JAR file itself (since it starts with PK). Why not use the following code to read the text file:
Main.class.getResourceAsStream("/readme.txt")
That would give you an InputStream to the text file without doing the hassle of opening the JAR file, etc.
You can then pass the InputStream object to the readFileToArray method (instead of the File object) and use
br = new BufferedReader(new InputStreamReader(inputStream));
The rest of your code should not need any change.
This seems to be an encoding problem. FileReader doesn't allow you to specify that. Try using
br = new BufferedReader(new InputStreamReader(new FileInputStream(file), yourEncoding));
You seem to be making far too much work for yourself here. You start by calling getResource, which gives you a URL to the readme.txt entry inside your JAR file, but then you take that URL, determine the JAR file that it is pointing inside, then open that JAR file with a FileInputStream and read the whole JAR file.
You can instead simply call .openStream() on the original URL that getResource returned, and this will give you an InputStream from which you can read the content of readme.txt
br = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
(if readme.txt is not encoded in UTF-8 then change that parameter as appropriate)
I wrote some code to read in a text file and to return an array with each line stored in an element. I can't for the life of me work out why this isn't working...can anyone have a quick look? The output from the System.out.println(line); is null so I'm guessing there's a problem reading the line in, but I can't see why. Btw, the file i'm passing to it definitely has something in it!
public InOutSys(String filename) {
try {
file = new File(filename);
br = new BufferedReader(new FileReader(file));
bw = new BufferedWriter(new FileWriter(file));
} catch (Exception e) {
e.printStackTrace();
}
}
public String[] readFile() {
ArrayList<String> dataList = new ArrayList<String>(); // use ArrayList because it can expand automatically
try {
String line;
// Read in lines of the document until you read a null line
do {
line = br.readLine();
System.out.println(line);
dataList.add(line);
} while (line != null && !line.isEmpty());
br.close();
} catch (Exception e) {
e.printStackTrace();
}
// Convert the ArrayList into an Array
String[] dataArr = new String[dataList.size()];
dataArr = dataList.toArray(dataArr);
// Test
for (String s : dataArr)
System.out.println(s);
return dataArr; // Returns an array containing the separate lines of the
// file
}
First, you open a FileWriter once after opening a FileReader using new FileWriter(file), which open a file in create mode. So it will be an empty file after you run your program.
Second, is there an empty line in your file? if so, !line.isEmpty() will terminate your do-while-loop.
You're using a FileWriter to the file you're reading, so the FileWriter clears the content of the file. Don't read and write to the same file concurrently.
Also:
don't assume a file contains a line. You shouldn't use a do/while loop, but rather a while loop;
always close steams, readers and writers in a finally block;
catch(Exception) is a bad practice. Only catch the exceptions you want, and can handle. Else, let them go up the stack.
I'm not sure if you're looking for a way to improve your provided code or just for a solution for "Reading in text file in Java" as the title said, but if you're looking for a solution I'd recommend using apache commons io to do it for you. The readLines method from FileUtils will do exactly what you want.
If you're looking to learn from a good example, FileUtils is open source, so you can take a look at how they chose to implement it by looking at the source.
There are several possible causes for your problem:
The file path is incorrect
You shouldn't try to read/write the same file at the same time
It's not such a good idea to initialize the buffers in the constructor, think of it - some method might close the buffer making it invalid for subsequent calls of that or other methods
The loop condition is incorrect
Better try this approach for reading:
try {
String line = null;
BufferedReader br = new BufferedReader(new FileReader(file));
while ((line = br.readLine()) != null) {
System.out.println(line);
dataList.add(line);
}
} finally {
if (br != null)
br.close();
}
I'm having trouble reading in XML data from an XML resource located in /res/xml/testxml.xml. For some reason using examples from my book and online, I'm not able to read the data properly. The following method is simple; read the XML resource and print the lines within it.
public InputStream fetchLocalStream(String file){
InputStream in = null;
try {
//in = Global.gContext.openFileInput("testxml.xml");
in = Global.gContext.getResources().openRawResource(R.xml.testxml);
try {
if (in != null) {
// prepare the file for reading
InputStreamReader inputreader = new InputStreamReader(in);
BufferedReader buffreader = new BufferedReader(inputreader);
String line;
// read every line of the file into the line-variable, on line at the time
while (( line = buffreader.readLine()) != null) {
Log.d(Global.TAG,"-->Line:" + line);
// do something with the settings from the file
}
}
} catch (Exception e){}
return in;
}catch (Exception e){ Log.d(Global.TAG,"--> Failed!!!!" + e); }
return in;
}
Any help would be greatly appreciated.
Line:└Ç└Ç└Ç∩┐╜∩┐╜∩┐╜∩┐╜♥└Ç└Ç└Ç#└Ç└Ç└Ƕ└Ƕ└Ç└Ç└Ç└Ç└Ç└Ç└Ç└Ç└Ç♦☺►└Ç∟└Ç└Ç└Ç
Line:└Ç└Ç└Ç∩┐╜∩┐╜∩┐╜∩┐╜$└Ç└Ç└└Ç└Ç└Ç└Ç└Ç└Ç└Ç♥☺►└Ç↑└Ç└Ç└Ç
Line:└Ç└Ç└Ç∩┐╜∩┐╜∩┐╜∩┐╜♥└Ç└Ç└Ç#└Ç└Ç└Ç☻☺►└Ç$└Ç└Ç└Ç
Line:└Ç└Ç└Ç∩┐╜∩┐╜∩┐╜∩┐╜♥└Ç└Ç└Ç%└Ç└Ç└Ƕ└Ƕ└Ç└Ç└Ç└Ç└Ç└Ç└Ç└Ç└Ç♦☺►└Ç∟└Ç└Ç└Ç
Line:└Ç└Ç└Ç∩┐╜∩┐╜∩┐╜∩┐╜&└Ç└Ç└└Ç└Ç└Ç└Ç└Ç└Ç└Ç♥☺►└Ç↑└Ç└Ç└Ç
Line:└Ç└Ç└Ç∩┐╜∩┐╜∩┐╜∩┐╜♥└Ç└Ç└Ç%└Ç└Ç└Ç☻☺►└ÇL└Ç└Ç└Ç
I had the same problem and found the solution in the thread "Android SAX xml not well-formed" over at anddev.org:
Found out an interesting stuff - when moving xml file from xml folder to raw, everything works smoothly. I guess that's why the function is called openRawResource .
Anyways i think that android adds some stuff to the files stored in non raw folder. But this is just a thinking aloud.
Moving from /res/xml to /res/raw solved the problem for me.
The problem is probably a character encoding issue. Try using the XmlResourceParser, which you can obtain via Resources.getXml. (Most XML parsers are adapt at dealing with character encoding.) Here's an example.
http://developer.android.com/reference/android/content/res/Resources.html