My Constructor for the filepath ist not working, JAVA - java

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.

Related

JAVA - not able to update data in file that is "resources" folder

I am a little perplexed by the behavior I see in my proof-of-concept test program.
My Java application uses a file that is placed in "resource" folder in the Java project. The application will occasionally read numeric data from it, use it, increment the number and write it back to the same file for the next cycle.
The following test application mimics the above (wanted) behavior:
public class ReadWriteFile {
private static final String TEMP_EMAIL_ID_DATAFILE_PATH = "main/resources/TempEmailId.dat";
public static void main(String[] args) throws ParseException {
try {
int id = readTempId();
System.out.println("Current value = " + id);
writeTempId(id+5);
System.out.println("Updated value = " + readTempId());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static int readTempId() throws IOException {
InputStream is = ReadWriteFile.class.getClassLoader().getResourceAsStream(TEMP_EMAIL_ID_DATAFILE_PATH);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = null;
int currentValue = 0;
while ((line = br.readLine()) != null) {
currentValue = Integer.parseInt(line);
}
br.close();
return currentValue;
}
public static void writeTempId(int currentId) throws IOException {
BufferedWriter bw = new BufferedWriter(new FileWriter("src" + File.separator + TEMP_EMAIL_ID_DATAFILE_PATH));
bw.write(Integer.toString(Math.abs(currentId)));
bw.flush();
bw.close();
return;
}
}
When I run the test, the following is seen:
Current value = 100000054
Updated value = 100000054
My gut feeling is that the use of
ReadWriteFile.class.getClassLoader().getResourceAsStream(TEMP_EMAIL_ID_DATAFILE_PATH);
is causing the issue. I am using this to access the file within the JAVA project.
Can it be true?
Also, note that for creating the BufferedWriter object, I have to pre-pend the Java constant with "src/" - else the file could not be found :(
Thanks.
Resources are intended to be read-only. The only way they could become writable is if they were extracted into the file system, but that's not how they are intended to be used and is not portable as resources are normally in a jar. Write to a file instead
This should work:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URISyntaxException;
import java.net.URL;
import java.text.ParseException;
public class ReadWriteFile {
private static final String TEMP_EMAIL_ID_DATAFILE_PATH = "TempEmailId.dat";
public static void main(String[] args) throws ParseException, URISyntaxException {
try {
int id = readTempId();
System.out.println("Current value = " + id);
writeTempId(id+5);
System.out.println("Updated value = " + readTempId());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static int readTempId() throws IOException {
InputStream is = ReadWriteFile.class.getClassLoader().getResourceAsStream(TEMP_EMAIL_ID_DATAFILE_PATH);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = null;
int currentValue = 0;
while ((line = br.readLine()) != null) {
currentValue = Integer.parseInt(line);
}
br.close();
return currentValue;
}
public static void writeTempId(int currentId) throws IOException, URISyntaxException {
URL resource = ReadWriteFile.class.getClassLoader().getResource(TEMP_EMAIL_ID_DATAFILE_PATH);
File file = new File(resource.toURI());
BufferedWriter bw = new BufferedWriter(new FileWriter(file));
bw.write(Integer.toString(Math.abs(currentId)));
bw.flush();
bw.close();
return;
}
}
The 2 key lines for writing to file was doing it as such:
URL resource = ReadWriteFile.class.getClassLoader().getResource(TEMP_EMAIL_ID_DATAFILE_PATH);
File file = new File(resource.toURI());

Reading numbers from a file and creating an array (java)

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
}
}
}

Calling a Jsonreader class for twitch streams

Ive encountered a little problem.
I made a json url checker that checks if a twitch.tv stream is either online or offline.
That one thing is handled in a seperate class TwitchLiveChecker.java.
Now i want to call that class with a timer all X minutes but somehow i dont understand how to call the class.
This is how i call it;
public void LiveChecker() {
TTtwl.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
try {
TwitchLiveChecker.startup(); *<- THIS Doesnt work :(*
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(TwitchLiveChecker.json);
System.out.println(TwitchLiveChecker.json);
}
}, 1000*10, 1000*10);
}
and this is my TwitchLiveChecker class File;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.nio.charset.Charset;
import org.json.JSONException;
import org.json.JSONObject;
public class TwitchLiveChecker {
public static JSONObject json;
private static String readAll(Reader rd) throws IOException {
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
return sb.toString();
}
public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
InputStream is = new URL(url).openStream();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String jsonText = readAll(rd);
JSONObject json = new JSONObject(jsonText);
return json;
} finally {
is.close();
}
}
public static void startup(String[] args) throws IOException, JSONException {
json = readJsonFromUrl("http://api.justin.tv/api/stream/list.json?channel="+MyBot.ownerchannel+"");
System.out.println(json.toString());
System.out.println(json.get("id"));
}
}
Im thankful for any hints or examples on what im doing wrong :D
You are not passing parameters to a method that requires them. Since TwitchLiveChecker.startup() doesn't use the args parameter, you should remove it. Your method signature should be public static void startup(), not public static void startup(String[] args)
Also, threads and static data (specifically your public static JSONObject json; don't mix well. Depending on what your thread pool is doing, you could have multiple threads writing to your static json object at the same time, corrupting the data in it.

null pointer exception in reading tsv file

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.

File always seems to be empty

Ok, I'm really confused by some code I wrote. It's a DataSetter (didn't know a better name for it...), and has methods to change the data in my data file (data.txt). This data has the following format: #key=value (eg. #version=1.0). Now, I tried to run this line of code:
new DataSetter().setValue("version", "1.1");
It just clears the file. That's pretty much all it does. Now, I think it clears the file because it makes a new File, which is completely empty but has the same name. Here's my code:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
/**
* This class contains methods to set specific data in the data.txt file. <br>
* The data is rewritten every time a new value is set.
*
* #author Casper van Battum
*
*/
public class DataSetter {
private static final File DATA_FILE = new File("resources/data.txt");
private static final String lineFormat = "#%s=%s";
private FileOutputStream out;
private DataReader reader = new DataReader();
private HashMap<String, String> dataMap = reader.getDataMap();
private Scanner scanner;
public DataSetter() {
try {
out = new FileOutputStream(DATA_FILE, false);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public void setValue(String key, String newValue) {
openDataFile();
String oldLine = String.format(lineFormat, key, dataMap.get(key));
dataMap.put(key, newValue);
String newLine = String.format(lineFormat, key, newValue);
try {
replace(oldLine, newLine);
} catch (IOException e) {
e.printStackTrace();
}
closeDataFile();
}
private void replace(String oldLine, String newLine) throws IOException {
ArrayList<String> tmpData = new ArrayList<String>();
while (scanner.hasNextLine()) {
String currentLine = scanner.nextLine();
tmpData.add((currentLine == oldLine) ? newLine : currentLine);
}
out.write(new String().getBytes());
String sep = System.getProperty("line.separator");
StringBuffer sb = new StringBuffer();
for (String string : tmpData) {
sb.append(string + sep);
}
FileWriter writer = new FileWriter(DATA_FILE);
String outString = sb.toString();
writer.write(outString);
writer.close();
}
private void openDataFile() {
try {
scanner = new Scanner(DATA_FILE);
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}
}
private void closeDataFile() {
scanner.close();
}
}
So after running the setValue() method, I just have an empty file...
Im really out of idea's on how to solve this...
You are truncating your data file with the
new FileOutputStream(DATA_FILE, false)
so no nothing is written when you go to output your the elements in the tmpData ArrayList read from Scanner.
ArrayList<String> tmpData = new ArrayList<String>();
while (scanner.hasNextLine()) {
String currentLine = scanner.nextLine(); // never gets called
...
}
The typical strategy for updating a text file is to create a temporary file with old file's contents (File#renameTo), write the data to file, then delete the temporary file after closing any open streams to the file being read.

Categories