This question already has answers here:
How can I avoid ArrayIndexOutOfBoundsException or IndexOutOfBoundsException? [duplicate]
(2 answers)
Closed 7 years ago.
i have wrote the code to read a 3rd column of a file(treeout1.txt) and write those contents in another file(tree.txt).and now i want to open tree.txt and write the contents to stem.txt,where tree.txt contents a single word in each row and a delimiter is found at the end of each line.i have attached that txt file below.you can view that to have better understanding.now i want to write the words into a line till a delimiter "###" is found...for example 'the girl own paper' and next line vol and so on....i have tried that but ArrayIndexOutOfBoundsException comes for a[]...why?and how to resolve that?
the text file tree.txt is given below
the
girl
own
paper
###
vol
###
viii
###
no
###
#card#
###
October
#card#
#card#
###
price
one
penny
###
as
the
baron
have
conjecture
the
housemaid
whom
he
have
call
out
of
the
nursery
to
look
for
###
lons
cane
on
find
her
master
have
go
without
it
do
not
hurry
back
but
stop
talk
###
Code:
package simple;
import java.io.*;
import java.util.Scanner;
import java.util.StringTokenizer;
public class Simple {
public static void main(String[] args) throws IOException {
String line;
String line2;
String[] a = new String[100];
int i = 0;
try {
BufferedReader br = new BufferedReader(new FileReader("C:/TreeTagger/treeout1.txt"));
BufferedWriter output = new BufferedWriter(new FileWriter("D:/tree.txt"));
String separator = System.getProperty("line.separator");
while ((line = br.readLine()) != null) {
StringTokenizer st2 = new StringTokenizer(line, "\n");
while (st2.hasMoreElements()) {
String line1 = (String) st2.nextElement();
String[] array = line1.split("\\s+", 3);
//System.out.println(array[2]);
output.append(array[2]);
output.newLine();
}
}
output.close();
br.close();
BufferedReader br1 = new BufferedReader(new FileReader("D:/tree.txt"));
BufferedWriter out = new BufferedWriter(new FileWriter("D:/stem.txt"));
while ((line2 = br1.readLine()) != null) {
StringTokenizer st = new StringTokenizer(line2, " ");
while (st.hasMoreTokens()) {
String element = st.nextToken();
System.out.println(element);
while (element != "###") {
a[i] = element;
i++;
}
out.append(a[i]);
element = element.replace(element, "");
}
}
} catch (IOException e) {
}
}
}
You need to reset i to 0 after you find the ### delimiter. Otherwise you will keep incrementing i until it gets larger than 100 (a's maximum).
Also you can't use the != operator on Strings (from your code: element != "###"). You need to use the following:
!"###".equals(element);
Related
I am trying to display the contents of multiple rows in a text file. I can do it no problem with a single line, but I add another line and I'm not sure what I need to add to my code to make it move on to the next line. I need myValues[1] to be the same as myValues[n] only to be the second line in the file. I believe I need to se a new String as the next line but I'm not sure exactly how with this setup.
package a3;
import java.io.*;
public class A3
{
public static void main(String [] args)
{
String animals = "animals.txt";
String line = null;
try
{
FileReader fileReader = new FileReader(animals);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String aLine = bufferedReader.readLine();
String myValues[] = aLine.split(" ");
int n = 0;
while((line = bufferedReader.readLine()) != null)
{
System.out.println(myValues[n] + " " + myValues[1]);
n++;
}
bufferedReader.close();
}
catch(FileNotFoundException ex)
{
System.out.println("Unable to open file '" + animals + "'");
}
catch(IOException ex)
{
System.out.println("Error reading file '" + animals + "'");
}
}
}
Here is another simple way to read lines from a file and do the processing:
There is a java.io.LineNumberReader class which helps do it.
Sample snippet:
LineNumberReader lnr = new LineNumberReader(new FileReader(new File(filename)));
String line = null;
while ((line = lnr.readLine()) != null)
{
// Do you processing on line
}
In your code, the array myValues is never changed and always contains the values for the first line of text. You need to change it each time you get a new line, this is done in your while loop :
[...]
while((line = bufferedReader.readLine()) != null)
{
myValues[] = line.split(" ");
System.out.println(myValues[n] + " " + myValues[1]);
n++;
}
Obviously not tested...
You could also read all lines to a String list like this:
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.util.List;
List<String> lines = Files.readAllLines(new File(animals).toPath(), Charset.defaultCharset());
And than iterate over the line list, split the values and output them.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
My code is supposed to read a file line by line, to put each one in a string array named: tuples, (tuples=ligne.split(" "); ) and then add this tuples to an arraylist, one line read = one element of the arraylist.
Unfortunately, my code doesn't work! My buffered reader throws a NullPointerException in my loop!
Error returned in the ExtractFile() method, line 120: tuples= ligne.split(" ");
File file = new File("Department.txt");
BufferedReader in;
PrintWriter out;
String ligne;
int nbCols; //number of metadatas in my file.txt
String metadata[] = new String[nbCols];
String[] tuples = new String[nbCols];//1ere case indique num ligne
ArrayList<String[]> itemset = new ArrayList<String[]>();
public ArrayList ExtractionFile () {
try {
int i = 1;
in = new BufferedReader(new FileReader(file));
while ((ligne = in.readLine()) != null) {
while (ligne.charAt(0) != '1') {
ligne = in.readLine();//browse until line 1 is found
}
tuples = ligne.split(" ");
itemset.add(tuples);
System.out.println(Arrays.toString(itemset.get(0)));
for (i = 2; i < TuplesCount(); i++) {
ligne = in.readLine();
tuples = ligne.split(" ");// THIS LINE THROWS THE EXCEPTION
itemset.add(tuples);
System.out.println(Arrays.toString(itemset.get(i)));
}
}
} catch (IOException es) {
es.printStackTrace();
} catch (ArrayIndexOutOfBoundsException exepti) {
exepti.printStackTrace();
}
return itemset;
}
A NullpointerException tells you that your code
attempts to use null in a case where an object is required. These include:
Calling the instance method of a null object.
...
In your case, you've told us that the error occurs on
tuples = ligne.split(" ");
You're trying to call split on ligne and - given the documentation quote above - that implies that ligne is null at that point.
It's worth noting that it is the second occurence of that line that throws the Exception, so it is not as simple as the file not having a line that starts with 1
Why?
You need to use a debugger or use lots of System.out.println to convince yourself how the value of ligne changes as your code executes and, crucially, where it becomes null.
In your case - we don't know what TuplesCount() returns, but the likelihood is that you keep iterating in that loop beyond the end of the file, so the line immediately before the one that fails
ligne = in.readline();
can return null and you never check for that at that point. Note that conditions for the loops are only checked after each iteration of the loop - so , except for the one right at the top in the condition of the while loop, all the calls to ligne = in.readline(); could return null and are never checked.
The code you provide us is really unreadable and should be formatted to easy debug it. Instead, you can try this simple code that i have tested on my IDE
package example;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
public class FileSplit {
public static void main(String[] args) {
ArrayList<String[]> phrases = new ArrayList<String[]>();
try{
BufferedReader in = new BufferedReader(new FileReader("Department.txt"));
String s;
while((s = in.readLine()) != null){
String[] words = s.split(" ");
phrases.add(words);
}
}catch(Exception e){
e.printStackTrace();
}
for(int i=0;i<phrases.size();i++){
for(int j=0;j<phrases.get(i).length;j++)
System.out.println(phrases.get(i)[j]);
}
}
}
Are you testing this with a file which doesn't contain a line 1? If so, you run this it will keep executing the inner loop despite the fact that the value is null, resulting in an exception the time after the last line has been read. To fix this change the inner loop to be an if.
Like so:
public ArrayList ExtractionFile() {
try {
int i = 1;
in = new BufferedReader(new FileReader(file));
ligne = in.readLine(); //It can be more readable to seperate the assignment and the condtion
while (ligne != null) {
if (ligne.charAt(0) != '1') {
ligne = in.readLine();//browse until line 1 is found
} else {
tuples = ligne.split(" ");
itemset.add(tuples);
System.out.println(Arrays.toString(itemset.get(0)));
for (i = 2; i < TuplesCount(); i++) {
ligne = in.readLine();
tuples = ligne.split(" ");// CETTE LIGNE SOULEVE L EXCEPTION
itemset.add(tuples);
System.out.println(Arrays.toString(itemset.get(i)));
}
}
}
} catch (IOException es) {
es.printStackTrace();
} catch (ArrayIndexOutOfBoundsException exepti) {
exepti.printStackTrace();
}
return itemset;
}
private int TuplesCount() {
return Arrays.asList(tuples).size();
}
public static void main(String[] args){
Main main = new Main();
main.ExtractionFile();
}
}
As per some of the points above, please do format your code - it makes it easier to get help! Also, read up on breakpoints!
I would like to store only the first column that is contained in the .txt file.
hello28 23232
hello27 23232
hello25 12321
This is the code I have so far, however at the moment it stores every line in the file; how can I make it so that only the first column is stored (The one which contains the user names of the users)?
public static boolean checkUserExists(String userName){
String line = "";
ArrayList <String> userNames = new ArrayList <String>();
try{
FileReader fr = new FileReader("investments.txt");
BufferedReader br = new BufferedReader(fr);
while((line = br.readLine()) != null) {
userNames.add(line);
}
}
catch(IOException e){
System.out.println("File not found!");
}
if (userNames.contains(userName)){
return false;
}
else{
return true;
}
}
All you need to do is just to split each line using whitespace as a delimiter and keep the first token, and repeat that for every line:
This can be achieved using the following line of code which uses the split function (see more info here http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String))
line.split("\\s+");
Then, the zero-th (0) element contains the first column, as you wish to do
There you go a fully working class:
import java.io.IOException;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
class white {
public static void main(String[] args) {
String line = "";
String username = "";
ArrayList <String> userNames = new ArrayList <String>();
try{
FileReader fr = new FileReader("investments.txt");
BufferedReader br = new BufferedReader(fr);
while((line = br.readLine()) != null) {
line.split("\\s+");
userNames.add(line.split("\\s+")[0]);
System.out.println(line.split("\\s+")[0]);
}
}
catch(IOException e){
System.out.println("File not found!");
}
}
}
OUTPUT:
hello28
hello27
hello25
You can extract the part of the line preceding the first space:
userNames.add(line.substring(0, line.indexOf(' ') ));
I want to read a text file containing space sepearted values. Values are integers. How can I read it? I want to read each line and after go to next.
The contents are as the example:
"12/11/2012" "00.00.01" 0,100
"12/11/2012" "00.00.05" 0,140
"12/11/2012" "00.00.09" 0,240
"12/11/2012" "00.00.13" 0,247
The first column is the date, the second is second and the third is litres.
How can I do it with a Java program?
I think of using Scanner class. I made this program:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ScannerExample {
public static void main(String args[]) throws FileNotFoundException {
File text = new File("C:\Users\Desktop\test\test.txt");
Scanner scnr = new Scanner(text);
int lineNumber = 1;
while(scnr.hasNextLine()){
String line = scnr.nextLine();
System.out.println("line " + lineNumber + " :" + line);
lineNumber++;
}
}
}
But I haven't the result that I would like to have.
Any help?
The easiest in Java is to use Apache Commons Libraries.
Just add the following dependency in your pom file (if you are using maven)
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-io</artifactId>
<version>1.3.2</version>
</dependency>
Then you can do
File file = new File("yourFile.txt");
List<String> lines = FileUtils.readLines(file);
You will get each of line of your file in the list. Then to get the content of your file:
for(String line : lines){
String[] columns = line.split(" ") //because your columns seem to be separated by a white space
}
The array columns will contain your data
DateFormat format = new SimpleDateFormat("dd/mm/yyyy");
//column 1
Date date = format.format(column[0]);
//column 2
//I'm not sure to get your second column, is it just second or can it be more?
//column 3
double litres = Double.parseDouble(column[2]);
This looks like a CSV file. You could use a CSV tool to read it.
I know CSV means 'comma separated values', and your file doesn't have commas, but CSV tools can also read files separated by space.
This would be done by simple google search as well.. first you would find code like this:
import java.io.*;
class FileRead
{
public static void main(String args[])
{
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("textfile.txt");
// Use DataInputStream to read binary NOT text.
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println (strLine);
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
Replace the System.out.println with some code to get all content from " to " Like:
while ((strLine = br.readLine()) != null) {
int start = 1, pos = 0,lastpos= 1;
String dates, times, values;
if(strLine.indexOf("\"",lastpos) > 0){
pos = strLine.indexOf("\"",lastpos);
dates = strLine.substring(start,pos);
lastpos = pos+3;//replace through search for \"
pos = strLine.indexOf("\"",lastpos);
times = strLine.substring(lastpos,pos);
lastpos = pos+2;//replace through search for \"
values = strLine.substring(lastpos,strLine.length());
System.out.println(dates);//Convert to Date
System.out.println(times);//Convert to time
System.out.println(values);//Convert to Integer.valueOf/)
System.out.println("next line");
}
}
I am implementing a RPN calculator in Java and need help creating a class to parse the equations into separate tokens.
My input file will have an unknown number of equations similar to the ones shown below:
49+62*61-36
4/64
(53+26)
0*72
21-85+75-85
90*76-50+67
46*89-15
34/83-38
20/76/14+92-15
I have already implemented my own generic stack class to be used in the program, but I am now trying to figure out how to read data from the input file. Any help appreciated.
I've posted the source code for my stack class at PasteBin, in case it may help.
I have also uploaded the Calculator with no filereading to PasteBin to show what I have done already.
I have now managed to get the file read in and the tokens broken up thanks for the help. I am getting an error when it reaches the end of the file and was wondering how to solve that?
Here is the code:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.StringTokenizer;
public class TestClass {
static public void main(String[] args) throws IOException {
File file = new File("testEquations.txt");
String[] lines = new String[10];
try {
FileReader reader = new FileReader(file);
BufferedReader buffReader = new BufferedReader(reader);
int x = 0;
String s;
while((s = buffReader.readLine()) != null){
lines[x] = s;
x++;
}
}
catch(IOException e){
System.exit(0);
}
String OPERATORS = "+-*/()";
for (String st : lines) {
StringTokenizer tokens = new StringTokenizer(st, OPERATORS, true);
while (tokens.hasMoreTokens()) {
String token = tokens.nextToken();
if (OPERATORS.contains(token))
handleOperator(token);
else
handleNumber(token);
}
}
}
private static void handleNumber(String token) {
System.out.println(""+token);
}
private static void handleOperator(String token) {
System.out.println(""+token);
}
}
Also How would I make sure the RPN works line by line? I am getting quite confused by the algorithms I am trying to follow.
Because all of the operators are single characters, you can instruct StringTokenizer to return them along with the numeric tokens.
String OPERATORS = "+-*/()";
String[] lines = ...
for (String line : lines) {
StringTokenizer tokens = new StringTokenizer(line, OPERATORS, true);
while (tokens.hasMoreTOkens()) {
String token = tokens.nextToken();
if (OPERATORS.contains(token))
handleOperator(token);
else
handleNumber(token);
}
}
As your question has now changed completely from it's original version - this is in response to your original one, which was how to use FileReader to get the values from your file.
This will put each line into a separate element of a String array. You should probably use an ArrayList instead, as it's far more flexible, but I have just done this as a quick demo - you can clean it up as you wish, although I notice the code you are using expects a String array as it's input. Perhaps you could read the values initially into an ArrayList, then copy that to an array once you have all the lines - that way you can put as many lines in as you wish and keep your code flexible for changes in the number of lines in your input file.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class TestClass {
static public void main(String[] args) {
File file = new File("myfile.txt");
String[] lines = new String[10];
try {
FileReader reader = new FileReader(file);
BufferedReader buffReader = new BufferedReader(reader);
int x = 0;
String s;
while((s = buffReader.readLine()) != null){
lines[x] = s;
x++;
}
}
catch(IOException e){
//handle exception
}
// And just to prove we have the lines right where we want them..
for(String st: lines)
System.out.println(st);
}
}
You mentioned before that you were using the code on this link:
http://www.technical-recipes.com/2011/a-mathematical-expression-parser-in-java/#more-1658
This appears to already deal with operator precedence doesn't it? And with parsing each String from the array and sorting them into numbers or operators? From my quick look it at least it appears to do that.
So it looks like all you need is for your lines to be in a String array, which you then pass to the code you already have. From what I can see anyway.
Obviously this doesn't address the issue of numbers greater than 9, but hopefully it helps with the first half.
:-)
public void actionPerformed(ActionEvent e) {
double sum=0;
int count = 0 ;
try {
String nomFichier = "Fichier.txt";
FileReader fr = new FileReader(nomFichier);
BufferedReader br = new BufferedReader(fr);
String ligneLue;
do {
ligneLue = br.readLine();
if(ligneLue != null) {
StringTokenizer st = new StringTokenizer(ligneLue, ";");
String nom = st.nextToken();
String prenom = st.nextToken();
String age = st.nextToken();
String tele = st.nextToken();
String adress = st.nextToken();
String codePostal = st.nextToken();
String ville = st.nextToken();
String paye = st.nextToken();
double note = Double.parseDouble(st.nextToken());
count++;
}
}
while(ligneLue != null);
br.close();
double mediane = count / 2;
if(mediane % 2 == 0) {
JOptionPane.showMessageDialog(null, "Le mediane dans le fichier est " + mediane);
}
else {
mediane +=1;
JOptionPane.showMessageDialog(null, "Le mediane dans le fichier est " + mediane);
}
}//fin try
catch(FileNotFoundException ex) {
System.out.println(ex.getMessage());
}
catch(IOException ex) {
System.out.println(ex.getMessage());
}
}