Null Pointer Exception Occurs only while comparison and not printing out values - java

public static void main(String[] args) throws FileNotFoundException, IOException {
// TODO code application logic here
BufferedReader in1 = new BufferedReader(new FileReader("595231gov_nov_13_assessed.txt"));
BufferedReader in2 = new BufferedReader(new FileReader("627231farsidetect.txt"));
String Id = null;
int count = 0;
String count_line=null;
while((count_line = in1.readLine()) != null){
if(count_line.contains("ID: "))
count ++;
}
System.out.println(count);
File1 [] File_1 = new File1[count];
in1 = new BufferedReader(new FileReader("595231gov_nov_13_assessed.txt"));
int i = 0;
String line = null;
String relation = null;
while ((line = in1.readLine()) != null && i != count){
if(line.contains("ID:")){
File_1 [i] = new File1();
File_1[i].ID = line;
}
else if(line.contains("Relation:")){
File_1[i].Relation = line;
}
else if(line.contains("Result:")){
File_1[i].Result = line;
i ++;
}
else if(line.contains("TP") || line.contains("FP") || line.contains("TN") || line.contains("FN")){
File_1[i-1].Comment = line;
}
}
line = null;
relation = null;
i =0;
int count2 = 0;
count_line=null;
while((count_line = in2.readLine()) != null){
if(count_line.contains("ID: "))
count2 ++;
}
System.out.println(count2);
in2 = new BufferedReader(new FileReader("/home/627231farsidetect.txt"));
File2 [] File_2 = new File2[count2];
while ((line = in2.readLine()) != null && i != count2){
if(line.contains("ID:")){
File_2 [i] = new File2();
File_2[i].ID = line;
}
else if(line.contains("Relation:")){
File_2[i].Relation = line;
}
else if(line.contains("Result:")){
File_2[i].Result = line;
i ++;
}
}
in1.close();
in2.close();
for (i=0; i<File_1.length - 1; i++)
{
System.out.println(File_1[i].ID);
System.out.println(File_1[i].Relation);
System.out.println(File_1[i].Result);
if(File_1[i].Comment != null)
System.out.println(File_1[i].Comment);
}
for (i=0; i<File_2.length; i++)
{
System.out.println(File_2[i].ID);
System.out.println(File_2[i].Relation);
System.out.println(File_2[i].Result);
}
for (i = 0; i < File_1.length-1; i++){
for(int j=0;j< File_2.length; i++){
if(File_1[i].ID != null && File_2[j].ID != null && File_1[i].Relation != null && File_2[j].Relation !=null){
if(File_1[i].ID.equals(File_2[j].ID) && File_1[i].Relation.equals(File_2[j].Relation)){
if(!(File_1[i].Result.equals(File_2[j].Result))){
System.out.println(File_1[i].ID);
System.out.println(File_1[i].Relation);
System.out.println(File_1[i].Result);
if(File_1[i].Comment != null)
System.out.println(File_1[i].Comment);
}
}
}
}
}
}
public static class File1{
public String ID;
public String Relation;
public String Result;
public String Comment;
public File1() {
this.Result = null;
this.ID=null;
this.Relation = null;
this.Comment = null;
}
}
public static class File2{
public String ID;
public String Relation;
public String Result;
public File2() {
this.Result = null;
this.ID=null;
this.Relation = null;
}
}
-When I just printout the values, I do not face a null pointer exception,
-But when I try and do comparison I am faced with a null pointer exception and I can't figure out why.
-NetBeans just points to the comparison statement
if(File_1[i].ID.equals(File_2[j].ID) && File_1[i].Relation.equals(File_2[j].Relation))
Something else which is unusual is that, I have assigned values for File_1 until File_1[Length] but it prints out length - 1 values. Whereas I assigned values for File_2 the same way and it prints fine. Please help. I am processing Farsi text, so there might be the possibility of weird characters, but I am pretty sure there has to be something to do with the index values.

Don't know if it was intentional or not, but in your for loop you seem to be incrementing the wrong value (i instead of j)...
for (i = 0; i < File_1.length-1; i++)
{
for(int j=0;j< File_2.length; j++)
{
if(File_1[i].ID != null && File_2[j].ID != null && File_1[i].Relation != null && File_2[j].Relation !=null)
{
if(File_1[i].ID.equals(File_2[j].ID) && File_1[i].Relation.equals(File_2[j].Relation))
{
if(!(File_1[i].Result.equals(File_2[j].Result)))
{
System.out.println(File_1[i].ID);
System.out.println(File_1[i].Relation);
System.out.println(File_1[i].Result);
if(File_1[i].Comment != null)
System.out.println(File_1[i].Comment);
}
}
}
}
}

Related

Populate DefaultTableModel from test file

I have this text file:
A
B
3.00
A
B
3.00
and my view is:
I want to match each row with each column(first_row-first_column,second_row-second_column, etc..) Where have I made a mistake?
My code is as follows:
BufferedReader infile = new BufferedReader(reader);
String line = "";
int counter = 0;
String title = "";
String author = "";
String price = "";
try {
while ((line = infile.readLine()) != null) {
++counter;
if (counter == 1) {
title = line;
} else if (counter == 2) {
author = line;
} else if (counter == 3) {
price = line;
SimpleBook sb = new SimpleBook(title, author, price);
bookList.add(sb);
counter = 0;
}
}
} catch (IOException ex) {
Logger.getLogger(SimpleBookList.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
you can do this as there is an blank line in your input file .
BufferedReader infile = new BufferedReader(reader);
String line = "";
int counter = 0;
String title = "";
String author = "";
String price = "";
try {
while ((line = infile.readLine()) != null) {
if(line.isEmpty())
continue;
++counter;
if (counter == 1) {
title = line;
} else if (counter == 2) {
author = line;
} else if (counter == 3) {
price = line;
SimpleBook sb = new SimpleBook(title, author, price);
bookList.add(sb);
counter = 0;
}
}
} catch (IOException ex) {
Logger.getLogger(SimpleBookList.class.getName()).log(Level.SEVERE, null, ex);
}
Your counter is incrementing at the begining of loop, so you never have 0 but 1 on if statement. Then empty line is parsed as 1 and goes to A column. You can solve it in multpile ways like skip empty lines or increment counter if line is not empty.

How to eliminate empty columns to be inserted to DB if CSV files contains empty columns?

I have a table in database with 5 columns. In CSV file I have data like below. How to process it into Oracle database by elimating empty columns (because CSV file contains 6 columns, it will mismatch in database columns having 5 columns).
111, ,John,2000, ,US
222, ,Alle,3000, ,China
333, ,Kite,4000,LCD,IND
444, ,King,5000,LED,Aust
package com.java;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.List;
import java.util.Vector;
public class Test3
{
public static void main(String[] args)
{
try
{
int commas = 0;
List data = new Vector();
List columnCount = new Vector();
String[] cols = null;
String[] strArray = null;
String file = "D:/temp/CSV/data.csv";
BufferedReader br = new BufferedReader(new FileReader(file));
String line = br.readLine();
do
{
commas = 0;
cols = line.split(",");
strArray = new String[cols.length];
int i=0;
for (String element : cols)
{
if (!isBlank(element))
{
strArray[i] = element;
i++;
}
}
int newFile = line.length();
for(int k = 0; k < newFile; k ++ )
{
char eachChar = line.charAt(k);
if(eachChar == ',')
{
commas ++;
}
}
data.add(strArray);
line = br.readLine();
}
while (line != null);
Vector columns = new Vector(commas + 1);
for(int i = 0; i < commas +1 ; i ++ )
{
columns.add("" + i);
}
} catch (Exception e) {
}
}
public static boolean isBlank(String str) {
int strLen;
if (str == null || (strLen = str.length()) == 0)
{
return true;
}
for (int i = 0; i < strLen; i++)
{
if ((Character.isWhitespace(str.charAt(i)) == false)) {
return false;
}
}
return true;
}
}
You can use a util method to check if it is empty string or not.
public static boolean isBlank(String str) {
int strLen;
if (str == null || (strLen = str.length()) == 0) {
return true;
}
for (int i = 0; i < strLen; i++) {
if ((Character.isWhitespace(str.charAt(i)) == false)) {
return false;
}
}
return true;
}
and use it in your reader like below
Scanner s = null;
try {
s = new Scanner(new File("D:/sri/Test.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
while (s.hasNextLine()) {
String[] line = s.nextLine().split(",");
for (String element : line) {
if (!isBlank(element))
System.out.println(element);
}
}

Compiler thinks final instance variable not initialised

My compiler is warning me that that an instance variable, a 2d int[][] array, might not have been initialised when I go to assign it.
I understand why the compiler might think that, because it is initialised in a double if statement. However the first if is on a boolean that is initialised to true, and the second if throws an exception on the else. I am confident of the logic of the program but the compiler obviously is not.
Does anyone have any tips for overcoming this kind of problem? I don't want to otherwise initialise the variable because it is meant to be final.
The variable of concern is the board variable. The below is part of a constructor for the object which contains the variable.
try {
FileReader fr = new FileReader(filename);
BufferedReader br = new BufferedReader(fr);
boolean first = true;
int lineCount = 0;
String line;
while ((line = br.readLine()) != null) {
String lineParts[] = line.split(" ");
if (first) {
if (lineParts.length == 2) {
this.xSize = Integer.parseInt(lineParts[0]);
this.ySize = Integer.parseInt(lineParts[1]);
board = new int[this.ySize][this.xSize];
first = false;
} else { throw new RuntimeException(); }
} else {
lineCount++;
if (lineParts.length == this.xSize) {
for (int i = 0; i < this.xSize; i++) {
board[lineCount][i] = Integer.parseInt(lineParts[i]);
}
} else throw new RuntimeException();
}
}
br.close();
if (lineCount != this.ySize) throw new RuntimeException();
}
Indeed, the compiler can't unravel the loop logic enough to know the final variable is initialized before use.
You'll need to move handling of the first line out of the loop — which is reasonable anyway, since the content of the loop is almost completely different for the first line and subsequent lines:
try {
FileReader fr = new FileReader(filename);
BufferedReader br = new BufferedReader(fr);
int lineCount = 0;
String line;
line = br.readLine();
if (line != null) {
String lineParts[] = line.split(" ");
if (lineParts.length == 2) {
this.xSize = Integer.parseInt(lineParts[0]);
this.ySize = Integer.parseInt(lineParts[1]);
board = new int[this.ySize][this.xSize];
} else {
throw new RuntimeException();
}
while ((line = br.readLine()) != null) {
String lineParts[] = line.split(" ");
lineCount++;
if (lineParts.length == this.xSize) {
for (int i = 0; i < this.xSize; i++) {
board[lineCount][i] = Integer.parseInt(lineParts[i]);
}
} else {
throw new RuntimeException();
}
}
}
br.close();
if (lineCount != this.ySize) throw new RuntimeException();
}
Note: This code preserves the previous code's behavior that it doesn't count the first line. I'm guessing the fact it's special includes not counting it. :-)
Side note: I'd strongly recommend using try-with-resources in that code, not only for best practices, but because you're not closing the file when you throw your exceptions:
try (
FileReader fr = new FileReader(filename);
BufferedReader br = new BufferedReader(fr);
) {
int lineCount = 0;
String line;
line = br.readLine();
if (line != null) {
String lineParts[] = line.split(" ");
if (lineParts.length == 2) {
this.xSize = Integer.parseInt(lineParts[0]);
this.ySize = Integer.parseInt(lineParts[1]);
board = new int[this.ySize][this.xSize];
} else {
throw new RuntimeException();
}
while ((line = br.readLine()) != null) {
String lineParts[] = line.split(" ");
lineCount++;
if (lineParts.length == this.xSize) {
for (int i = 0; i < this.xSize; i++) {
board[lineCount][i] = Integer.parseInt(lineParts[i]);
}
} else {
throw new RuntimeException();
}
}
}
if (lineCount != this.ySize) throw new RuntimeException();
}

Java - Comparing two huge text files

I am trying to develop a basic java program to compare two huge text files and print non matching records .i.e. similar to minus function in SQL. but I am not getting the expected results because all the records are getting printed even though both files are same. Also suggest me whether this approach is performance efficient for comparing two huge text files.
import java.io.*;
public class CompareTwoFiles {
static int count1 = 0 ;
static int count2 = 0 ;
static String arrayLines1[] = new String[countLines("\\Files_Comparison\\File1.txt")];
static String arrayLines2[] = new String[countLines("\\Files_Comparison\\File2.txt")];
public static void main(String args[]){
findDifference("\\Files_Comparison\\File1.txt","\\Files_Comparison\\File2.txt");
displayRecords();
}
public static int countLines(String File){
int lineCount = 0;
try {
BufferedReader br = new BufferedReader(new FileReader(File));
while ((br.readLine()) != null) {
lineCount++;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return lineCount;
}
public static void findDifference(String File1, String File2){
String contents1 = null;
String contents2 = null;
try
{
FileReader file1 = new FileReader(File1);
FileReader file2 = new FileReader(File2);
BufferedReader buf1 = new BufferedReader(file1);
BufferedReader buf2 = new BufferedReader(file2);
while ((contents1 = buf1.readLine()) != null)
{
arrayLines1[count1] = contents1 ;
count1++;
}
while ((contents2 = buf2.readLine()) != null)
{
arrayLines2[count2] = contents2 ;
count2++;
}
}catch (Exception e){
e.printStackTrace();
}
}
public static void displayRecords() {
for (int i = 0 ; i < arrayLines1.length ; i++) {
String a = arrayLines1[i];
for (int j = 0; j < arrayLines2.length; j++){
String b = arrayLines2[j];
boolean result = a.contains(b);
if(result == false){
System.out.println(a);
}
}
}
}
}
Based upon your explanation you do not need embedded loops
consider
public static void displayRecords() {
for (int i = 0 ; i < arrayLines1.length && i < arrayLines2.length; i++)
{
String a = arrayLines1[i];
String b = arrayLines2[i];
if(!a.contains(b){
System.out.println(a);
}
}
For the performance wise, you should try to match the size of the files. If the sizes(in bytes) are exactly the same, you might not need to compare them.

Java - Writing a Method to Count Lines In a Text File Without Throwing Exceptions

Below is a solution from Number of lines in a file in Java
to quickly count the number of lines in a text file.
However, I am trying to write a method that will perform the same task without throwing an 'IOException'.
Under the original solution is my attempt to do this with a nested try-catch block <-- (Is this usually done/frowned upon/ or easily avoidable??) which returns 0 no matter how many lines are in the given file (obviously a fail).
Just to be clear, I am not looking for advice on how to better use the original method that does contain the exception and, therefore, the context within which I am using it is irrelevant to this question.
Can somebody please help me write a method that counts the number of lines in a text file and does not throw any exceptions? (In other words, deals with potential errors with a try-catch.)
Original line counter by martinus:
public static int countLines(String filename) throws IOException {
InputStream is = new BufferedInputStream(new FileInputStream(filename));
try {
byte[] c = new byte[1024];
int count = 0;
int readChars = 0;
boolean empty = true;
while ((readChars = is.read(c)) != -1) {
empty = false;
for (int i = 0; i < readChars; ++i) {
if (c[i] == '\n') {
++count;
}
}
}
return (count == 0 && !empty) ? 1 : count;
} finally {
is.close();
}
}
My Attempt:
public int countLines(String fileName ) {
InputStream input = null;
try{
try{
input = new BufferedInputStream(new FileInputStream(fileName));
byte[] count = new byte[1024];
int lines = 0;
int forChar;
boolean empty = true;
while((forChar = input.read(count)) != -1){
empty = false;
for(int x = 0; x < forChar; x++){
if(count[x] == '\n'){
lines++;
}
}
}
return (!empty && lines == 0) ? 1 : lines + 1;
}
finally{
if(input != null)
input.close();
}
}
catch(IOException f){
int lines = 0;
return lines;
}
}
It is more robust to use char instead of byte for '\n' and return -1 in case of any errors, for example if the filename does not exist:
public static int countLines(String filename) {
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(new FileInputStream(filename)));
char[] c = new char[1024];
int count = 0;
int readChars = 0;
boolean emptyLine = true;
while ((readChars = br.read(c)) != -1) {
for (int i = 0; i < readChars; ++i) {
emptyLine = false;
if (c[i] == '\n') {
++count;
emptyLine = true;
}
}
}
return count + (!emptyLine ? 1 : 0);
} catch (IOException ex) {
return -1;
} finally {
if (br != null)
try {
br.close();
} catch (IOException e) {
// Ignore intentionally
}
}
}
Sharing my attempt.
public static int countLines(String filename) {
InputStream is = new BufferedInputStream(new FileInputStream(filename));
int numLines = 0;
try {
byte[] c = new byte[1024];
int count = 0;
int readChars = 0;
boolean empty = true;
while ((readChars = is.read(c)) != -1) {
empty = false;
for (int i = 0; i < readChars; ++i) {
if (c[i] == '\n') {
++count;
}
}
}
numLines = (count == 0 && !empty) ? 1 : count;
} catch (IOException ex) {
numLines = 0;
} catch (FileNotFoundException ex) {
System.out.println("File not found.");
numLines = 0;
} finally {
is.close();
}
return numLines;
}

Categories

Resources