hi can anybody help me with below code. why this is throwing null pointer exception and how i can avoid it.
i am trying to read a tsv file and csv file and do some processing with this.
when i am calling getDictionaryValues function it throwing null pointer exception.
package com.ugam.qa.tittle;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class TittleMatch {
private static TittleMatchUtil tMU;
public static void main(String[] args) {
String fullname="d:/files/listing/Headphones.tsv";
Set<String> attributeSet=new HashSet<String>();
attributeSet.add("Storage Type");
attributeSet.add("Recording Definition");
attributeSet.add("Type");
attributeSet.add("Brand");
BufferedReader in = null;
try
{
System.out.println("file found");
in= new BufferedReader(new FileReader(fullname));
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
String str;
String prv_Pid="-1";
try {
str = in.readLine();
while ((str = in.readLine()) != null) {
if (str.trim().length() == 0 ) {
System.out.println("while loop");
continue;}
String[] values = str.split("\\t");
//System.out.println(values.length);
if(prv_Pid=="-1" || values[9]==prv_Pid)
{
if(attributeSet.contains(values[12]))
{
ArrayList<Set<String>> dicValues=new ArrayList<Set<String>>();
if(values[12]!=null && values[13]!=null)
{
dicValues=tMU.getDictionaryValues(values[12],values[13]);
}
//Set<String> tittle=new HashSet<String>();
//tittle.add(values[8]);
//System.out.println(tittle);
}
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Obviously this variable is evaluated to null, since you never assign a value to it.
private static TittleMatchUtil tMU;
One solution would be assigning a new TittleMatchUtil object to the variable:
private static TittleMatchUtil tMU = new TittleMatchUtil();
and another one is to make the getDictionaryValues() method static, which I wouldn't do, because it may require more code re-factoring.
Related
If I use the filepath directly in the class CtoJ it works.
If i pass it through the constructor it gives me a Nullpointer.
Well I do not know what I could add to make my problem any more clear.
Well if I use String path =""; it throws no such file or directory.
It seems like the constructor is not able to write the filepath into the path variable?
public class CSVReader {
public static void main(String[] args) {
CtoJ test = new CtoJ("/Users/peterg/Desktop/test.csv");
}
}
import org.json.CDL;
import org.json.JSONArray;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class CtoJ {
private String path;
private StringBuilder content = new StringBuilder();
private String line;
private String stringtoJSON;
public CtoJ(String path) {
this.path = path;
}
{
try {
BufferedReader reader = new BufferedReader(new FileReader(path));
while ((line = reader.readLine()) != null) {
content.append(removeUnnecessaryQuotes(line));
content.append(System.lineSeparator());
}
stringtoJSON = content.toString();
JSONArray jsonArray = CDL.toJSONArray(stringtoJSON);
System.out.println(jsonArray);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static String removeUnnecessaryQuotes(String s) {
String withoutQuotes;
withoutQuotes = s.substring(0).replaceAll("\"", "");
withoutQuotes.substring(0).replaceAll("\"\"", "\"");
return withoutQuotes;
}
}
Here is some of the data I use, if u want to test it:
FID,OBJECTID,SHAPE,LAGE,GRILLPLATZ_ID,RESERVIERUNG,WEBLINK1,SE_ANNO_CAD_DAT
"GRILLPLATZOGD.6748,6748,POINT (16.465255884594104 48.19018769574157),""22., Donauinsel, ca. 350 Meter stromab der Steinspornbrücke (Inselmitte, Erdwall)"",15,ja,http://www.wien.gv.at/amtshelfer/umwelt/wasserbau/donauinsel/grillplatzreservierung.html,"
"GRILLPLATZOGD.6749,6749,POINT (16.48177464603615 48.183356069714286),""22., Neue Donau, linkes Ufer, zwischen Steinspornbrücke und Waluliso Brücke (bei km 5,1) (Dammbereich) "",16,ja,http://www.wien.gv.at/amtshelfer/umwelt/wasserbau/donauinsel/grillplatzreservierung.html,"
"GRILLPLATZOGD.6750,6750,POINT (16.460158556964053 48.177745677669925),""11., Donaukanal, Alberner Hafenzufahrtsstraße, Nähe Margetinstraße"",0,nein,http://www.wien.gv.at/umwelt/wald/freizeit/grillen/,"
you get the error because you accidentally used an instance initializer block in your Code. That is
class Foo {
//constructor
public Foo() {
System.out.println("Constructor");
}
//instance initializer Block
{
System.out.println("Instance Initializer");
}
}
Generally, this is okay, however, the initializer block is executed before the constructor is.
In your particular example
BufferedReader reader = new BufferedReader(new FileReader(path));
in the initializer block is dependent on the instantiation of path in the constructor. So as a quick fix just move the code from the initializer to the constructor and you shouldn't get any NullPointerException.
I cannot figure out how to make this txt file with numbers into an array, I am able to get it to read and print the screen but I need to be able to organize the numbers and delete the duplicates. This is what my code looks like so far
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class File {
public static void main(String[] args) {
String filename = "C:/input.txt";
File rfe = new File();
rfe.readFile(filename);
}
private void readFile(String name) {
String input;
try (BufferedReader reader = new BufferedReader(new FileReader(name))) {
while((input = reader.readLine()) != null) {
System.out.format(input); // Display the line on the monitor
}
}
catch(FileNotFoundException fnfe) {
}
catch(IOException ioe) {
}
catch(Exception ex) { // Not required, but a good practice
}
}
}
I would recommend using an ArrayList rather than an Array.
With an array you would have to parse through the list and calculate the line count before you could even initialize it. An ArrayList is much more flexible as you don't have to declare how many values will be added to it.
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class File {
private List<Integer> data = new ArrayList<Integer>(); //Create ArrayList
public static void main(String[] args) {
String filename = "C:/input.txt";
File rfe = new File();
rfe.readFile(filename);
}
private void readFile(String name) {
String input;
try (BufferedReader reader = new BufferedReader(new FileReader(name))) {
while((input = reader.readLine()) != null) {
data.add(Integer.parseInt(input));//Add each parsed number to the arraylist
System.out.println(input); // Display the line on the monitor
}
}
catch(FileNotFoundException fnfe) {
}
catch(IOException ioe) {
}
catch(Exception ex) { // Not required, but a good practice
ex.printstacktrace(); //Usually good for general handling
}
}
}
For example we have a .txt file:
Name smth
Year 2012
Copies 1
And I want to replace it with that:
Name smth
Year 2012
Copies 0
Using java.io.*.
Here is the code that does that. Let me know if you have any question.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.LinkedHashMap;
import java.util.Map;
public class Test2 {
Map<String, String> someDataStructure = new LinkedHashMap<String, String>();
File fileDir = new File("c:\\temp\\test.txt");
public static void main(String[] args) {
Test2 test = new Test2();
try {
test.readFileIntoADataStructure();
test.writeFileFromADataStructure();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
private void readFileIntoADataStructure() throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(
new FileInputStream(fileDir)));
String line;
while ((line = in.readLine()) != null) {
if (line != null && !line.trim().isEmpty()) {
String[] keyValue = line.split(" ");
// Do you own index and null checks here this is just a sample
someDataStructure.put(keyValue[0], keyValue[1]);
}
}
in.close();
}
private void writeFileFromADataStructure() throws IOException {
Writer out = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(fileDir)));
for (String key : someDataStructure.keySet()) {
// Apply whatever business logic you want to apply here
myBusinessMethod(key);
out.write(key + " " + someDataStructure.get(key) + "\n");
out.append("\r\n");
out.append("\r\n");
}
out.flush();
out.close();
}
private String myBusinessMethod(String data) {
if (data.equalsIgnoreCase("Copies")) {
someDataStructure.put(data, "0");
}
return data;
}
}
Read your original text file line by line and separate them into string tokens delimited by spaces for output, then when the part you want replaced is found (as a string), replace the output to what you want it to be. Adding the false flag to the filewrite object ("filename.txt", false) will overwrite and not append to the file allowing you to replace the contents of the file.
this is the code to do that
try {
String sCurrentLine;
BufferedReader br = new BufferedReader(new FileReader("yourFolder/theinputfile.txt"));
BufferedWriter bw = new BufferedWriter(new FileWriter("yourFolder/theinputfile.txt" , false));
while ((sCurrentLine = br.readLine()) != null) {
if(sCurrentLine.indexOf("Copies")>=0){
bw.write("Copies 0")
}
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close()bw.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
hopefully that help
What is the correct syntax for creating a 2D array from a text file? This array must be string not char or int. None of the information I've found on this is for string, and I haven't been able to figure the exact syntax out myself.
You can use ArrayList object .Its internal implemetation is Resizable or growable array.
So you can achieve your requirement by ArrayList<String>.You can get even arry by using its utility methods.
For more details ArrayList docs
For sample click here
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class Read2DimensionFileToList {
public static void main(String[] args) {
String [][] sList=new String[100][2];
BufferedReader br = null;
try {
String s;
br = new BufferedReader(new FileReader("C:\\testing.txt"));
int i=0;
while ((s = br.readLine()) != null) {
String []sArray=s.split(",");
sList[i++][0]=sArray[0];
sList[i][1]=sArray[1];
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
ı read text. my text is like that
AYSE;SERDAR-9.8;EMRE-5.2;AYTAC-3.3
FATMA;OYTUN-8.8;ORKUN-7.5;ONUR-5.4;UMUT-4.4;BERK-3.3;CAN-3.2
DERYA;VELI-7.7;ALI-6.5;SUAT-6.0;YAVUZ-5.0;OYTUN-4.2;ORKUN-3.1
DILARA;DOGUS-8.8;VELI-7.4;ALI-6.5;SUAT-5.5;YAVUZ-3.1
BEGUM;SUAT-6.6;YAVUZ-5.1;OYTUN-4.3;ORKUN-4.0
BERIL;CANER-8.7;DOGUS-7.5;VELI-6.2;ALI-6.1;SUAT-5.8;YAVUZ-4.8;OYTUN-4.0
FUNDA;ORKUN-9.7;ONUR-8.3;UMUT-7.2;BERK-6.5;CAN-5.5
ISIL;AYTAC-8.3;CANER-7.4;DOGUS-6.5;VELI-5.5;ALI-5.4;SUAT-4.4;YAVUZ-4.0;OYTUN-3.9;ORKUN-3.5;ONUR-3.4;UMUT-3.2;BERK-3.1;CAN-3.0
ELIF;EMRE-7.4;AYTAC-6.1
ı cant add "u.eleman" and "u.uyum" values to "treeset tSU". it gives memory address when ı do syso ı cant see them in the tSU TREESET. I want to add all of them to treeset. How can ı do that.. please help
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.TreeSet;
public class Rapor {
static class Uyum implements Comparable<Uyum> {
String eleman;
Double uyum;
public int compareTo(Uyum u) {
if (uyum < u.uyum)
return -1;
if (uyum > u.uyum)
return 1;
return 0;
}
}
public static void main(String[] args) {
FileInputStream fIS;
try {
fIS = new FileInputStream("C:\\deneme\\rapor.txt");
Reader r;
r = new InputStreamReader(fIS, "UTF-8");
BufferedReader bR = new BufferedReader(r);
String satır;
String[] point, p2;
while ((satır = bR.readLine()) != null) {
point = satır.split(";");
String kelime = point[0];
HashMap<String, TreeSet<Uyum>> uyumlar = new HashMap<String, TreeSet<Uyum>>();
TreeSet<Uyum> tSU = new TreeSet<Uyum>() ;
Uyum u ;
for (int i = 1; i < point.length; i++) {
p2=point[i].split("\\-");
u = new Uyum();
u.eleman = p2[0];//EMRE,AYTAC,..
u.uyum = Double.parseDouble(p2
[1]);//7.8,9.5
tSU.add(u);
}
uyumlar.put(kelime, tSU);
System.out.println(uyumlar);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}// main end
}// class end
it gives memory address when ı do syso ı cant see them in the tSU TREESET.
No, it does not print the memory address. It prints the class name, an # and the hash code for the object in hexadecimal - that's what Object.toString() does by default.
If you want your Uyum objects to be printed differently, then override the toString() method in your class Uyum.