Dealing with txt file via split(), says Nullpointerexception - java

I know there are many similar questions here, but I still can't solve it. I can get all the results that I want. However, in the end, it still shows nullpointerexception. I don't know why. can anyone help?
public class PointGenterate {
public static void main(String[] args) throws FileNotFoundException {
// TODO Auto-generated method stub
try{
File file = new File("123.txt");
double[] pointsid = new double[10];
String[] data = null;
for(int i = 0; i <10; i++){
double rn = (int)(Math.random()*120);
System.out.println(rn);
pointsid[i] = rn;
}
//read file
InputStreamReader rs = new InputStreamReader(new FileInputStream(file));//create input stream reader object
BufferedReader br = new BufferedReader(rs);
String line = "";
line = br.readLine();
//
File write = new File("output.KML");
write.createNewFile();
BufferedWriter out = new BufferedWriter(new FileWriter(write));
while(line != null){
line = br.readLine();
if(line==" "){
System.out.print("empty");
}else{
data = line.split(",|:|[|]");
}
for(int i = 0; i < data.length; i++){
data[i] = data[i].trim();
System.out.println(data[i] + "num" + i);
}
if(data.length > 15){
double id = Double.parseDouble(data[4]);
for(int i = 0; i <10; i++){
if(id == pointsid[i]){
data[10] = data[10].substring(0, data[10].length()-2);
data[15] = data[15].substring(1,data[15].length());
data[16] = data[16].substring(0, data[16].length()-6);
out.write(data[8]+" "+ data[10]+ " " + data[13] + data[15] + data[16]+ "\r\n");
out.flush();
}
}
}
//System.out.println(line);
}
out.close();
}
catch(Exception e){
e.printStackTrace();
}
}
}
the txt file format is like
{ "type": "Feature", "properties": { "id": 126.000000, "osm_id": 4851918786.000000, "name": "Moray House Library", "type": "library" }, "geometry": { "type": "Point", "coordinates": [ -3.180841771200988, 55.950622362732418 ] } },
this is one line. I have many lines, and actually this is just a test code. if it works. i want to write it as a method in a javaseverlet class. get the string coordinates and return it to my JS font-end.

There's a few issues with your code. In this section:
InputStreamReader rs = new InputStreamReader(new FileInputStream(file));//create input stream reader object
BufferedReader br = new BufferedReader(rs);
String line = "";
line = br.readLine(); // here you read the first line in the file
//
File write = new File("output.KML");
write.createNewFile();
BufferedWriter out = new BufferedWriter(new FileWriter(write));
while(line != null){ // here you check that it's not null (it's not, you read the first line OK)
line = br.readLine(); // here you read the second line (there is no second line, now line is null)
if(line==" "){ // now you check if the line is a space character (this is wrong for 2 reasons, that's not how you compare strings, and a space character is not an empty string)
System.out.print("empty");
}else{
data = line.split(",|:|[|]"); // here you call split() on line but line is null
}
When you checked if the string was empty, you did line == " " which is wrong for 2 reasons. First you cannot use == to compare strings - read this question for details on why not. Second, " " is a string that contains a space character. "" is an empty string.
When you want to check if a string is empty you can do it like this:
line.equals("")
or like this:
line.isEmpty()
Here's your code with a few small changes so that it runs without throwing an exception.
public class PointGenterate {
public static void main(String[] args) throws Exception {
try {
File file = new File("123.txt");
double[] pointsid = new double[10];
String[] data = null;
for(int i = 0; i < 10; i++){
double rn = (int)(Math.random()*120);
System.out.println(rn);
pointsid[i] = rn;
}
//read file
InputStreamReader rs = new InputStreamReader(new FileInputStream(file));//create input stream reader object
BufferedReader br = new BufferedReader(rs);
String line = "";
//
File write = new File("output.KML");
write.createNewFile();
BufferedWriter out = new BufferedWriter(new FileWriter(write));
while((line = br.readLine()) != null){ // read the line and check for null
if(line.isEmpty()) { // is the line equal to the empty string?
System.out.print("empty");
} else {
data = line.split(",|:|[|]");
}
for(int i = 0; i < data.length; i++){
data[i] = data[i].trim();
System.out.println(data[i] + "num" + i);
}
if(data.length > 15){
double id = Double.parseDouble(data[4]);
for(int i = 0; i <10; i++){
if(id == pointsid[i]){
data[10] = data[10].substring(0, data[10].length()-2);
data[15] = data[15].substring(1,data[15].length());
data[16] = data[16].substring(0, data[16].length()-6);
out.write(data[8]+" "+ data[10]+ " " + data[13] + data[15] + data[16]+ "\r\n");
out.flush();
}
}
}
//System.out.println(line);
}
out.close();
}
catch(Exception e){
e.printStackTrace();
}
}
}

Related

How to get data from a CSV file and place it in a list

I want to read data from a CSV file in Java and then put this data into a list. The data in the CSV is put into rows which looks like:
Data, 32, 4.3
Month, May2, May 5
The code I have currently only prints the [32].
ArrayList<String> myList = new ArrayList<String>();
Scanner scanner = new Scanner(new File("\\C:\\Users\\Book1.csv\\"));
scanner.useDelimiter(",");
while(scanner.hasNext()){
myList.add(scanner.next());
for (int i = 0; i <= myList.size(); i++) {
System.out.println(myList.toString());
}
scanner.close();
}
Maybe this code can help you, maybe this code is different from yours, you use arrayList while I use regular array.
Example of the data:
Farhan,3.84,4,72
Rajab,2.98,4,72
Agil,2.72,4,72
Alpin,3.11,4,73
Mono,3,6,118 K
imel,3.97,7,132
Rano,2.12,6,110
Kukuh,4,1,22
Placing data on each row in a csv file separated by commas into the array of each index
int tmp = 0;
String read;
Mahasiswa[] mhs = new Mahasiswa[100];
BufferedWriter outs;
BufferedReader ins;
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
Scanner input = new Scanner(System.in);
try {
ins = new BufferedReader(new FileReader("src/file.csv"));
tmp = 0;
while ((read = ins.readLine()) != null) {
String[] siswa = read.split(",");
mhs[tmp] = new Mahasiswa();
mhs[tmp].nama = siswa[0];
mhs[tmp].ipk = Float.parseFloat(siswa[1]);
mhs[tmp].sem = Integer.parseInt(siswa[2]);
mhs[tmp].sks = Integer.parseInt(siswa[3]);
tmp++;
i++;
}
ins.close();
} catch (IOException e) {
System.out.println("Terdapat Masalah: " + e);
}
Print the array data
tmp = 0;
while (tmp < i) {
System.out.println(mhs[tmp].nama + "\t\t" +
mhs[tmp].ipk + "\t\t" +
mhs[tmp].sem + "\t\t" +
mhs[tmp].sks);
tmp++;
}
ArrayList<String> myList = new ArrayList<String>();
try (Scanner scanner = new Scanner(new File("C:\\Users\\Book1.csv"))) {
//here at your code there are backslashes at front and end of the path that was the
//main reason you are not able to read csv file
scanner.useDelimiter(",");
while (scanner.hasNext()) {
myList.add(scanner.next());
}
for (int i = 0; i < myList.size(); i++) { //remember index is always equal to "length - 1"
System.out.println(myList);
}
} catch (Exception e) {
e.printStackTrace();
}
you also did not handle the FileNotFoundException
Hope this helps:)

How to get text from a TextFile and putting it to a Table

I am trying to put text from a text file to a table I want it to display on the table when pressing a button. It does not display any errors it just does not work. Can someone please explain why and how to make it work. The text is divided with ;
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt)
{
try {
BufferedReader br = new BufferedReader(new
FileReader("zam.txt"));
String r;
int v =0;
do{
r = br.readLine();
if(r!=null){
v++;
}
}while(r!=null);
Object[] row = new String[v];
do{
r = br.readLine();
if(r!=null){
for (int i = 0; i < v; i++) {
int ix = r.indexOf(";");
row[i] = r.substring(0, ix);
r = r.substring(ix+1);
int zn = r.indexOf(";");
row[i] += r.substring(0, zn);
r = r.substring(zn+1);
int xn = r.indexOf(";");
row[i] += r.substring(0, xn);
r = r.substring(xn+1);
int an = r.indexOf(";");
row[i] += r.substring(0, an);
table.addRow(row);
}
}
}while(r!=null);
br.close();
} catch (IOException e) {
}
}
You should shorten this.
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt)
{
try {
BufferedReader br = new BufferedReader(new
FileReader("zam.txt"));
String r;
do{
r = br.readLine();
if(r!=null){
String [] sline=r.split(";");
table.addRow(sline);
}
}while(r!=null);
br.close();
} catch (IOException e) {
}
}
Reason: you read the file 2 times but without resetting the stream. Why?
Then you counted the number of lines and took this number as number of columns, why?
You count the number of lines in the file
do{
r = br.readLine();
if(r!=null){
v++;
}
}while(r!=null);
After that you try to read from the file, after the EOF has already been reached
do{
r = br.readLine();
if(r!=null){
[...]
}
}while(r!=null);
r = br.readLine(); will return null, since the EOF has been reached, and skip over the loop
To fix this, you can either reopen the file
//counting code
br.close();
br = new BufferedReader([...]);
//reading code
Or you can add the lines to a List instead, and use that
BufferedReader br = new BufferedReader([...]);
List<String> lines = new ArrayList<String>();
for(String line = br.readLine(); line != null; line = br.readLine())
lines.add(line);
String[] row = lines.toArray(new String[0]);
If you're just adding the values to a table, it may be easier to not store the file at all
BufferedReader br = new BufferedReader([...]);
for(String line = br.readLine(); line != null; line = br.readLine())
table.addRow(line.split(";"));

combine two methods in Java together in this Java code

I want combine the two methods Just some error in my document parser, frequencyCounter and parseFiles thsi code.
I want all of frequencyCounter should be a function that should be executed from within parseFiles, and relevant information don't worry about the file's content should be passed to doSomething so that it knows what to print.
Right now I'm just keep messing up on how to put these two methods together, please give some advices
this is my main class:
public class Yolo {
public static void frodo() throws Exception {
int n; // number of keywords
Scanner sc = new Scanner(System.in);
System.out.println("number of keywords : ");
n = sc.nextInt();
for (int j = 0; j <= n; j++) {
Scanner scan = new Scanner(System.in);
System.out.println("give the testword : ");
String testWord = scan.next();
System.out.println(testWord);
File document = new File("path//to//doc1.txt");
boolean check = true;
try {
FileInputStream fstream = new FileInputStream(document);
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
strLine = br.readLine();
// Read File Line By Line
int count = 0;
while ((strLine = br.readLine()) != null) {
// check to see whether testWord occurs at least once in the
// line of text
check = strLine.toLowerCase().contains(testWord.toLowerCase());
if (check) {
// get the line
String[] lineWords = strLine.split("\\s+");
// System.out.println(strLine);
count++;
}
}
System.out.println(testWord + "frequency: " + count);
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
The code below gives you this output:
Professor frequency: 54
engineering frequency: 188
data frequency: 2
mining frequency: 2
research frequency: 9
Though this is only for doc1, you've to add a loop to iterate on all the 5 documents.
public class yolo {
public static void frodo() throws Exception {
String[] keywords = { "Professor" , "engineering" , "data" , "mining" , "research"};
for(int i=0; i< keywords.length; i++){
String testWord = keywords[i];
File document = new File("path//to//doc1.txt");
boolean check = true;
try {
FileInputStream fstream = new FileInputStream(document);
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
strLine = br.readLine();
// Read File Line By Line
int count = 0;
while ((strLine = br.readLine()) != null) {
// check to see whether testWord occurs at least once in the
// line of text
check = strLine.toLowerCase().contains(testWord.toLowerCase());
if (check) {
// get the line
String[] lineWords = strLine.split("\\s+");
count++;
}
}
System.out.println(testWord + "frequency: " + count);
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
hope this helps!

java.util.NoSuchElementException: No line found*

I keep getting this error
java.util.NoSuchElementException No line found
when I use this method
public boolean hasMoreCommands() {
if (input.hasNextLine()) {
return true;
} else {
//input.close();
return false;
}
}
public void advance() {
String str;
if(hasMoreCommands() == true){
do {
str = input.nextLine().trim();
// Strip out any comments
if (str.contains("//")) {
str = (str.substring(0, str.indexOf("//"))).trim();
}
} while (str.startsWith("//") || str.isEmpty() || hasMoreCommands());
command = str;
}
}
I have main code here:
public class Ptest
{
public Ptest(String fileName)
{
String line = null;
String nName = fileName.replace(".vm", ".asm");
Parser p = new Parser();
try{
File neF = new File(nName);
if(!neF.exists()){
neF.createNewFile();
}
File tempFile = new File("temp.txt");
if(!tempFile.exists()){
tempFile.createNewFile();
}
FileReader fr = new FileReader(fileName);
BufferedReader br = new BufferedReader(fr);
FileWriter fw = new FileWriter(nName);
BufferedWriter bw = new BufferedWriter(fw);
FileWriter writR = new FileWriter(tempFile);
BufferedWriter buffR = new BufferedWriter(writR);
while((line = br.readLine()) != null) {
buffR.write(line+ "\n");
//System.out.println(line);
}
buffR.flush();
buffR.close();
p.insertTitle(tempFile);
String ctype = p.commandType();
int len = ctype.length();
int spaces = 13 - len;
String sp = " ";
String asp = " ";
String a1 = null;
int a2;
int alen;
boolean t = false;
while(p.hasMoreCommands()){
for(int i= 0; i < spaces; i++){
sp += " ";
}
t = p.hasMoreCommands();
a1 = p.arg1();
alen = (10 - a1.length());
for(int i= 0; i < alen; i++){
asp += " ";
}
//a2 = p.arg2();
if (ctype == "C_PUSH" || ctype == "C_POP" || ctype == "C_FUNCTION" || ctype == "C_CALL") {
a2 = p.arg2();
bw.write(ctype + sp + a1 + asp + a2);
}
else {
bw.write(ctype + sp + a1);
}
p.advance();
ctype = p.commandType();
len = ctype.length();
spaces = 13 - len;
}
bw.flush();
bw.close();
}
catch(FileNotFoundException ex){
System.out.println("File not found!");
}
catch(IOException ex){
System.out.println("Error reading file '" + fileName + "'");
}
}
}
I went through debugger and it literally goes the entire file then gives me an error when its finished.
Like #hfontanez I think your problem is in this code:
if(hasMoreCommands() == true){
do {
str = input.nextLine().trim();
// Strip out any comments
if (str.contains("//")) {
str = (str.substring(0, str.indexOf("//"))).trim();
}
} while (str.startsWith("//") || str.isEmpty() || hasMoreCommands());
command = str;
}
However, my solution is to change the while clause to while (str.isEmpty() && hasMoreCommands());
I'm assuming that "advance" ought to return the next non-comment / blank line.
If the string from the previous pass is empty (after stripping any comment) it will go round the loop again provided that wasn't the last line. But, if that was the last line or str still has something in it, then it will exit the loop. Comments should have been stripped so don't need tested for in the while.
I think if you just test for hasNextLine within the loop then it will never exit the loop if the last line was comment / blank.
My guess is that your problem is here:
if(hasMoreCommands() == true){
do {
str = input.nextLine().trim();
// Strip out any comments
if (str.contains("//")) {
str = (str.substring(0, str.indexOf("//"))).trim();
}
} while (str.startsWith("//") || str.isEmpty() || hasMoreCommands());
command = str;
}
The exception you encountered (NoSuchElementException) typically occurs when someone tries to iterate though something (String tokens, a map, etc) without checking first if there are any more elements to get. The first time the code above is executed, it checks to see if it has more commands, THEN it gets in a loop. The first time it should work fine, however, if the test done by the while() succeeds, the next iteration will blow up when it tries to do input.nextLine(). You have to check is there is a next line to be got before calling this method. Surround this line with an if(input.hasNextLine()) and I think you should be fine.

Java Reading 2D array in from file, numbers separated by comma

This is some code that I found to help with reading in a 2D Array, but the problem I am having is this will only work when reading a list of number structured like:
73
56
30
75
80
ect..
What I want is to be able to read multiple lines that are structured like this:
1,0,1,1,0,1,0,1,0,1
1,0,0,1,0,0,0,1,0,1
1,1,0,1,0,1,0,1,1,1
I just want to essentially import each line as an array, while structuring them like an array in the text file.
Everything I have read says to use scan.usedelimiter(","); but everywhere I try to use it the program throws straight to the catch that replies "Error converting number". If anyone can help I would greatly appreciate it. I also saw some information about using split for the buffered reader, but I don't know which would be better to use/why/how.
String filename = "res/test.txt"; // Finds the file you want to test.
try{
FileReader ConnectionToFile = new FileReader(filename);
BufferedReader read = new BufferedReader(ConnectionToFile);
Scanner scan = new Scanner(read);
int[][] Spaces = new int[10][10];
int counter = 0;
try{
while(scan.hasNext() && counter < 10)
{
for(int i = 0; i < 10; i++)
{
counter = counter + 1;
for(int m = 0; m < 10; m++)
{
Spaces[i][m] = scan.nextInt();
}
}
}
for(int i = 0; i < 10; i++)
{
//Prints out Arrays to the Console, (not needed in final)
System.out.println("Array" + (i + 1) + " is: " + Spaces[i][0] + ", " + Spaces[i][1] + ", " + Spaces[i][2] + ", " + Spaces[i][3] + ", " + Spaces[i][4] + ", " + Spaces[i][5] + ", " + Spaces[i][6]+ ", " + Spaces[i][7]+ ", " + Spaces[i][8]+ ", " + Spaces[i][9]);
}
}
catch(InputMismatchException e)
{
System.out.println("Error converting number");
}
scan.close();
read.close();
}
catch (IOException e)
{
System.out.println("IO-Error open/close of file" + filename);
}
}
I provide my code here.
public static int[][] readArray(String path) throws IOException {
//1,0,1,1,0,1,0,1,0,1
int[][] result = new int[3][10];
BufferedReader reader = new BufferedReader(new FileReader(path));
String line = null;
Scanner scanner = null;
line = reader.readLine();
if(line == null) {
return result;
}
String pattern = createPattern(line);
int lineNumber = 0;
MatchResult temp = null;
while(line != null) {
scanner = new Scanner(line);
scanner.findInLine(pattern);
temp = scanner.match();
int count = temp.groupCount();
for(int i=1;i<=count;i++) {
result[lineNumber][i-1] = Integer.parseInt(temp.group(i));
}
lineNumber++;
scanner.close();
line = reader.readLine();
}
return result;
}
public static String createPattern(String line) {
char[] chars = line.toCharArray();
StringBuilder pattern = new StringBuilder();;
for(char c : chars) {
if(',' == c) {
pattern.append(',');
} else {
pattern.append("(\\d+)");
}
}
return pattern.toString();
}
The following piece of code snippet might be helpful. The basic idea is to read each line and parse out CSV. Please be advised that CSV parsing is generally hard and mostly requires specialized library (such as CSVReader). However, the issue in hand is relatively straightforward.
try {
String line = "";
int rowNumber = 0;
while(scan.hasNextLine()) {
line = scan.nextLine();
String[] elements = line.split(',');
int elementCount = 0;
for(String element : elements) {
int elementValue = Integer.parseInt(element);
spaces[rowNumber][elementCount] = elementValue;
elementCount++;
}
rowNumber++;
}
} // you know what goes afterwards
Since it is a file which is read line by line, read each line using a delimiter ",".
So Here you just create a new scanner object passing each line using delimter ","
Code looks like this, in first for loop
for(int i = 0; i < 10; i++)
{
Scanner newScan=new Scanner(scan.nextLine()).useDelimiter(",");
counter = counter + 1;
for(int m = 0; m < 10; m++)
{
Spaces[i][m] = newScan.nextInt();
}
}
Use the useDelimiter method in Scanner to set the delimiter to "," instead of the default space character.
As per the sample input given, if the next row in a 2D array begins in a new line, instead of using a ",", multiple delimiters have to be specified.
Example:
scan.useDelimiter(",|\\r\\n");
This sets the delimiter to both "," and carriage return + new line characters.
Why use a scanner for a file? You already have a BufferedReader:
FileReader fileReader = new FileReader(filename);
BufferedReader reader = new BufferedReader(fileReader);
Now you can read the file line by line. The tricky bit is you want an array of int
int[][] spaces = new int[10][10];
String line = null;
int row = 0;
while ((line = reader.readLine()) != null)
{
String[] array = line.split(",");
for (int i = 0; i < array.length; i++)
{
spaces[row][i] = Integer.parseInt(array[i]);
}
row++;
}
The other approach is using a Scanner for the individual lines:
while ((line = reader.readLine()) != null)
{
Scanner s = new Scanner(line).useDelimiter(',');
int col = 0;
while (s.hasNextInt())
{
spaces[row][col] = s.nextInt();
col++;
}
row++;
}
The other thing worth noting is that you're using an int[10][10]; this requires you to know the length of the file in advance. A List<int[]> would remove this requirement.

Categories