I am new to Android Development and Java. Please bear with me.
So, I am making an application which opens a random webpage from a list of webpage
The code reads a text file present in the assets folder which contains all the links, and makes a list of the links and then selects one at random.
So the problem is that I have put in log messages, to check if the program is reading and populating the array till the last line of the text.
The log messages show the size of the list as 1301. Whereas my text file contains 2601 links.
I can't to seem to understand where am I going wrong.
Here is the java code snippet,
int sd=0;
List<String> links=new ArrayList<>();
try {
AssetManager assetManager = getAssets();
InputStream assetIn = assetManager.open("android");
BufferedReader r = new BufferedReader(new InputStreamReader(assetIn));
while (r.readLine() != null) {
links.add(r.readLine());
sd++;
}
} catch (IOException e) {
e.printStackTrace();
}
Random r=new Random();
//String len= Integer.toString(links.size());
String len= Integer.toString(sd);
Log.i("total loop",len);
String randomLink=links.get(r.nextInt(links.size()));
Log.i("link select :",randomLink);
webView.loadUrl(randomLink);
You read line on loop twicely, here:
1) while (r.readLine() != null) {
2) links.add(r.readLine());
So it should be:
String line = "";
while ((line = r.readLine()) != null) {
links.add(line);
sd++;
}
You are calling readLine() twice, thus reading 2 lines instead of 1 on each iteration:
while (r.readLine() != null) { // reads a line
links.add(r.readLine()); // reads another line
sd++; // increments by 1 every *2* lines read
}
You probably wanted to use:
while ((line = r.readLine()) != null) {
links.add(line);
sd++;
}
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 have to make an EPG app using java, but I am kind of new in programming and it's due tomorrow and it's still not working properly.
I have a question about a small part: I have to read the programs from a text file. Each line contains multiple things, the channel, the title of the program, a subtitle, a category, etcetera.
I have to make sure that I can read the separate parts of each line, but it's not really working, it's only printing the parts from the first line.
I am trying, but I can't find why it's not printing all the parts from all the lines in stead of printing only the parts from the first line. Here's the code:
BufferedReader reader = new BufferedReader(newFileReader(filepath));
while (true) {
String line = reader.readLine();
if (line == null) {
break;
}
}
String[] parts = line.split("\\|", -1);
for(int i = 0; i < parts.length; i++) {
System.out.println(parts[i]);
}
reader.close();
Does anybody know how to get all the lines in stead of only the first?
Thank you!
readLine() only reads one line, so you need to loop it, as you said.
BUT with reading to the String inside of the while loop you always overwrite that String.
You would need to declare the String above the while loop that you can access it from outside, too.
BTW, it seems that your braces for the if don't match.
Anyway, I'd fill the information into an ArrayList, look below:
List<String> list = new ArrayList<>();
String content;
// readLine() and close() may throw errors, so they require you to catch it…
try {
while ((content = reader.readLine()) != null) {
list.add(content);
}
reader.close();
} catch (IOException e) {
// This just prints the error log to the console if something goes wrong
e.printStackTrace();
}
// Now proceed with your list, e.g. retrieve first item and split
String[] parts = list.get(0).split("\\|", -1);
// You can simplify the for loop like this,
// you call this for each:
for (String s : parts) {
System.out.println(s);
}
Use apache commons lib
File file = new File("test.txt");
List<String> lines = FileUtils.readLines(file);
As ArrayList is Dynamic,try,
private static List<String> readFile(String filepath) {
String line = null;
List<String> list = new ArrayList<String>();
try {
BufferedReader reader = new BufferedReader(new FileReader(filepath));
while((line = reader.readLine()) != null){
list.add(line);
}
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
I am designing a program that will load a text file into different media file classes (Media > Audio > mp3, Media > Video > Avi, etc).
Now the first line of my text file is how many files there are in total, as in
3
exmaple.mp3,fawg,gseges
test.gif,wfwa,rgeg
ayylmao.avi,awf,gesg
Now that is what is in my text file, I want to first get the first line separately, then loop through the rest of the files.
Now I understand I can simply count how many files are in by using an int that grows as I loop but I want it clear in the file aswell, and I'm not sure how to go about this.
static public Media[] importMedia(String fileName)
{
try {
BufferedReader reader = new BufferedReader(new FileReader(fileName));
String line = reader.readLine();
while(line != null)
{
//Get the first line of the text file seperatly? (Then maybe remove it? idk)
//Split string, create a temp media file and add it to a list for the rest of the lines
}
//String[] split = s.next().split(",");
} catch (Exception ex) { System.out.println(ex.getMessage()); }
return null;
}
I hope my question is clear, if it TL;DR I want to get the first line of a text file separately, then the rest Id like to loop through.
I wouldn't advice using a for-loop here, since the file might contain additional lines (e.g. comments or blank lines) to make it more human-readable. By examining the content of each line, you can make your processing more robust against this sort of thing.
static public Media[] importMedia(String fileName)
{
try {
BufferedReader reader = new BufferedReader(new FileReader(fileName));
// Get and process first line:
String line = reader.readLine(); // <-- Get the first line. You could consider reader as a queue (sort-of), where readLine() dequeues the first element in the reader queue.
int numberOfItems = Integer.valueOf(line); // <-- Create an int of that line.
// Do the rest:
while((line = reader.readLine()) != null) // <-- Each call to reader.readLine() will get the next line in the buffer, so the first time around this will give you the second line, etc. until there are no lines left to read.
{
// You will not get the header here, only the rest.
if(!line.isEmpty() || line.startsWith("#") {
// If the line is not empty and doesn't start with a comment character (I chose # here).
String[] split = line.split(",");
String fileName = split[0];
// etc...
}
}
} catch (Exception ex) { System.out.println(ex.getMessage()); }
return null;
}
You don't need while loop to read up to end of file. Read first line and convert it to int than loop through.
static public Media[] importMedia(String fileName)
{
try {
BufferedReader reader = new BufferedReader(new FileReader(fileName));
// Get and process first line:
int lineNo=Integer.parseInt(reader.readLine());
// Now read upto lineNo
for(int i=0; i < lineNo; i++){
//Do what you need with other lines.
String[] values = reader.readLine().split(",");
}
} catch (Exception e) {
//Your exception handling goes here
}
}
I was looking through a lot of diffrent subjects here on stackoverflow but couldn't find anything helpful so far :/
So this is my problem. I am writing a filecopier. The problem occurs already at reading the file. My test docoument got 3 lines of random text. All those 3 lines should get written in a string array. The problem is that only the 2nd line of the textdocument gets written in the array and I can't figure out why. Already debugged it, but didn't get me any further.
I know there are diffrent solutions for a filecopier with diffrent classes etc. But I would really like to get it running with the classes I used here.
String[] array = new String[5];
String datei = "test.txt";
public String[] readfile() throws FileNotFoundException {
FileReader fr = new FileReader(datei);
BufferedReader bf = new BufferedReader(fr);
try {
int i=0;
//String Zeile = bf.readLine();
while(bf.readLine() != null){
array[i] = bf.readLine();
// System.out.println(array[i]); This line is for testing
i++;
}
bf.close();
} catch (IOException e) {
e.printStackTrace();
}
return array;
You're calling readLine() twice for each iteration of the loop, thereby discarding every other line. You need to capture the value returned by every call to readLine(), because each readLine() call advances the reader's position in the file.
Here's the idiomatic solution:
String line;
while((line = bf.readLine()) != null){
array[i] = line;
i++;
}
Here you read 2 lines:
while(bf.readLine() != null){
array[i] = bf.readLine();
// System.out.println(array[i]); This line is for testing
i++;
}
You have to change your Code to:
String line = null;
while((line =bf.readLine()) != null){
array[i] = line;
// System.out.println(array[i]); This line is for testing
i++;
}
The problem is here :
while(bf.readLine() != null)
readLine() reads a line and returns the same at the same time it moves to the next line.
So instead of just checking if the returned value was null also store it.
String txt = null;
while((txt = bf.readLine()) != null)
array[i++] = txt;
I think its because you are calling readLine() twice. First time in the loop, and then second time when you put it in the array. So, it reads a line at the beginning of the loop (line 1), then first line of code inside the loop (line 2 that you see)
I am use Stream.
Not a. This form only applies to reading text files.
BufferedReader bf = new BufferedReader(fr);
// ...
List<String> lines = bf.lines().collect(Collectors.toList());
I have a text file with x amount of lines. each line holds a integer number. When the user clicks a button, an action is performed via actionlistener where it should list all the values as displayed on the text file. However, right now I have linenum set to 10 implying I already told the code that just work with 10 lines of the text file. So, if my text file has only 3 rows/lines of data...it will list those lines and for rest of the other 7 lines, it will spit out "null".
I recall there is a way to use ellipsis to let the program know that you don't know the exact value but at the end it calculates it based on the given information. Where my given information will the number of lines with numbers(data).
Below is part of the code.
private class thehandler implements ActionListener{
public void actionPerformed(ActionEvent event){
BufferedReader inputFile=null;
try {
FileReader freader =new FileReader("Data.txt");
inputFile = new BufferedReader(freader);
String MAP = "";
int linenum=10;
while(linenum > 0)
{
linenum=linenum-1;
MAP = inputFile.readLine();//read the next line until the specfic line is found
System.out.println(MAP);
}
} catch( Exception y ) { y.printStackTrace(); }
}}
just put instead of linenum > 0 the next line (MAP = inputFile.readLine()) != null
and delete the next lines, linenum=linenum-1;
MAP = inputFile.readLine(); and next time a bit of googling might help +)
The null value of the last line would not be printed because it sets the line to be the current line and compares it with the null value so if the last line is null it will not print it and what about the 10 lines limit? you can do it easily you can just add an an index to the for loop and to index and to check with && if the i is lower then 10
Test the value that comes back from BufferedReader.readLine(), if it is null stop looping, like so:
BufferedReader reader = new BufferedReader(new FileReader("Data.txt"));
try {
for (String line; (line = reader.readLine()) != null;) {
System.out.println(line);
}
} finally {
reader.close();
}
EDIT: forgot the requirement to take first 10 lines, you can change above code to put output in a list and return the list, then you can filter it through a function like this:
public List<String> takeFirst(int howMany, List<String> lines) {
return lines.size() <= howMany ? lines : lines.subList(0, howMany);
}
If the file is huge then this will be inefficient, of course, and if that matters you will end up doing something like:
BufferedReader reader = new BufferedReader(new FileReader("Data.txt"));
try {
int linesRead = 0;
for (String line; (line = reader.readLine()) != null && linesRead < 10;) {
System.out.println(line);
linesRead += 1;
}
} finally {
reader.close();
}
which is uglier but reads only the lines you need.
How about you don't print MAP if its value is null?