Error in write ArrayList String to File - java

I am trying to write an arraylist string list to a file. The arraylist string is actually a string converted from twitter JSON and I am trying to write the tweet text into the file.
However, I keep getting this error:
Exception in thread "main" java.lang.NullPointerException
at java.io.Writer.write(Unknown Source)
at kr.ac.uos.datamining.test.main(test.java:32)
The code for the whole class are below:
package kr.ac.uos.datamining;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import kr.ac.uos.datamining.JSONParser;
import kr.ac.uos.datamining.Tweet;
import kr.ac.uos.datamining.User;
public class test {
public static List <String> list = new ArrayList<String>();
public static void main(String[] args) throws IOException, FileNotFoundException, InterruptedException, SQLException {
JSONParser j = new JSONParser(new File("D:/curl-7.32.0/samsunggalaxy-01-23-2014.txt"));
ArrayList<Tweet> tweets = j.getTweets();
for(Tweet tweet : tweets){
list.add(tweet.getText());
}
FileWriter writer = new FileWriter("D:/samsunggalaxy.txt");
for (String tweet: list) {
Line 32 writer.write(tweet);
}
writer.close();
}
}
Since it is said as Unknown Source, is it the problem with the String tweet: list line?
I tried to change it to String str: list but its not working as well

The only way that you got a NullPoineterException is that your text is null, so validate what you want to write before writing it.
for (String tweet: list) {
if(tweet != null || !tweet.equals("")) {
writer.write(tweet);
}
}

Seems one of your tweet objects is null. This is the problem here.

It seems the String tweet is null, so I'd check your Tweet.getText() method to ensure it never returns null.

Related

Error occurred when importing the Html file in Jsoup

When I am importing the HTML File according to the tutorialpoint link https://www.tutorialspoint.com/jsoup/jsoup_load_file.htm
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
public class jsoupTester {
public static void main(String[] args) throws IOException, URISyntaxException {
URL path = ClassLoader.getSystemResource("test.htm");
File input = new File(path.toURI());
Document document = Jsoup.parse(input, "UTF-8", "");
System.out.println(document.title());
}
}
I got this error when I run the program:
Exception in thread "main" java.lang.NullPointerException
at jsoupTester.main(jsoupTester.java:13)
Note: jsoupTester.java file and temp.htm are in the same location
May I know how to solve this issue? Your suggestions will be highly appreciated :)
Have you checked the website properly? the code documentation showed this
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
public class JsoupTester {
public static void main(String[] args) throws IOException, URISyntaxException {
URL path = ClassLoader.getSystemResource("test.htm");
File input = new File(path.toURI());
Document document = Jsoup.parse(input, "UTF-8"); // Only 2 parameters
System.out.println(document.title());
}
}
Error
Document document = Jsoup.parse(input, "UTF-8", ""); // 3rd parameter is not included in the documentation
As you can see the error is that you have another redundant parameter which I believe is causing the error. Remove that "" in your code and it will work fine. Hope that answers your question :)

EDI Must be a minimum of 1 instances of segment [UNS]

Am newbie to EDI. And i just converted the ORDERS edi file to XML using smooks api. Some of the ORDER example files are working fine in following example. But i got the following exception when i running the following edi file. Am stuck with this. Here is my example and EDI data
package example;
import org.json.JSONObject;
import org.json.XML;
import org.milyn.Smooks;
import org.milyn.SmooksException;
import org.milyn.io.StreamUtils;
import org.milyn.smooks.edi.unedifact.UNEdifactReaderConfigurator;
import org.xml.sax.SAXException;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.StringWriter;
public class Main {
public static int PRETTY_PRINT_INDENT_FACTOR = 4;
protected static String runSmooksTransform() throws IOException, SAXException, SmooksException {
Smooks smooks = new Smooks();
smooks.setReaderConfig(new UNEdifactReaderConfigurator("urn:org.milyn.edi.unedifact:d93a-mapping:*"));
try {
StringWriter writer = new StringWriter();
smooks.filterSource(new StreamSource(new FileInputStream("EDI.edi")), new StreamResult(writer));
return writer.toString();
} finally {
smooks.close();
}
}
public static void main(String[] args) throws IOException, SAXException, SmooksException {
System.out.println("\n\n==============Message In==============");
System.out.println(readInputMessage());
System.out.println("======================================\n");
String messageOut = Main.runSmooksTransform();
System.out.println("==============Message Out=============");
System.out.println(messageOut);
System.out.println("======================================\n\n");
JSONObject xmlJSONObj = XML.toJSONObject(messageOut);
String jsonPrettyPrintString = xmlJSONObj.toString(PRETTY_PRINT_INDENT_FACTOR);
System.out.println(jsonPrettyPrintString);
}
private static String readInputMessage() throws IOException {
return StreamUtils.readStreamAsString(new FileInputStream("EDI.edi"));
}
}
And the exception with Sample EDI Data
Exception in thread "main" org.milyn.SmooksException: Failed to filter source.
at org.milyn.delivery.sax.SmooksSAXFilter.doFilter(SmooksSAXFilter.java:97)
at org.milyn.delivery.sax.SmooksSAXFilter.doFilter(SmooksSAXFilter.java:64)
at org.milyn.Smooks._filter(Smooks.java:526)
at org.milyn.Smooks.filterSource(Smooks.java:482)
at org.milyn.Smooks.filterSource(Smooks.java:456)
at example.Main.runSmooksTransform(Main.java:49)
at example.Main.main(Main.java:63)
Caused by: org.milyn.edisax.EDIParseException: EDI message processing failed [ORDERS][D:93A:UN]. Must be a minimum of 1 instances of segment [UNS]. Currently at segment number 9.
at org.milyn.edisax.EDIParser.mapSegments(EDIParser.java:499)
at org.milyn.edisax.EDIParser.mapSegments(EDIParser.java:450)
at org.milyn.edisax.EDIParser.parse(EDIParser.java:426)
at org.milyn.edisax.EDIParser.parse(EDIParser.java:410)
at org.milyn.edisax.unedifact.handlers.UNHHandler.process(UNHHandler.java:97)
at org.milyn.edisax.unedifact.handlers.UNBHandler.process(UNBHandler.java:75)
at org.milyn.edisax.unedifact.UNEdifactInterchangeParser.parse(UNEdifactInterchangeParser.java:113)
at org.milyn.smooks.edi.unedifact.UNEdifactReader.parse(UNEdifactReader.java:75)
at org.milyn.delivery.sax.SAXParser.parse(SAXParser.java:76)
at org.milyn.delivery.sax.SmooksSAXFilter.doFilter(SmooksSAXFilter.java:86)
... 6 more
Bad source data will cause this.
It looks like smooks is looking for a UNS segment which isn't in your data. The section control is mandatory per the D.93A standard.

Finding unique elements between two 2 TSV Files

Hi guys I am stuck with one of my problem assignments. I have tried different approaches but I'm still not able to do it.
I think this will do the trick. Process the old file first, then overwrite existing ones from the new file.
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
...
public class ContactsProcessor {
public static void main(String[] args) {
List<String> contactsNew = Files.readAllLines(Paths.get("contactsNew.tsv"));
List<String> contactsOld = Files.readAllLines(Paths.get("contactsOld.tsv"));
List<String> contactsGmail = new ArrayList<String>();
Map<String, String> gmailMap = new HashMap<String, String>();
// process old contacts first -- add to a Map
for (String info : contactsOld) {
String[] parts = info.split("\\t");
if (info.endsWith("#gmail.com")) {
gmailMap.put(parts[0], info);
}
}
// process new contacts second -- add to a Map, overwriting old contacts with same name
for (String info : contactsNew) {
String[] parts = info.split("\\t");
if (info.endsWith("#gmail.com")) {
gmailMap.put(parts[0], info);
}
}
contactsGmail.addAll(gmailMap.values());
Collections.sort(contactsGmail);
Files.write(Paths.get("contactsGmail.tsv"), contactsGmail);
}
}

JSON parser - write to text file - Exception in thread "main" java.lang.NullPointerException

I am trying to write a list JSON that has been parsed into ArrayList String to a txt file.
However I keep getting this error:
Exception in thread "main" java.lang.NullPointerException
at kr.ac.uos.datamining.JSONParser.parseForTweets(JSONParser.java:47)
at kr.ac.uos.datamining.JSONParser.<init>(JSONParser.java:25)
at kr.ac.uos.datamining.test.main(test.java:21)
This is the main class code test.java:
package kr.ac.uos.datamining;
import java.io.File;
import java.io.FileWriter;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import kr.ac.uos.datamining.JSONParser;
import kr.ac.uos.datamining.Tweet;
import kr.ac.uos.datamining.User;
public class test {
public static List <String> list = new ArrayList<String>();
public static void main(String[] args) throws IOException, FileNotFoundException, InterruptedException, SQLException {
**Line 21**
JSONParser j = new JSONParser(new File("D:/usr/samsunggalaxy.txt"));
ArrayList<Tweet> tweets = j.getTweets();
for(Tweet tweet : tweets){
User user = tweet.getUser();
list.add(tweet.getText() + " | " + user.getScreenName());
}
FileWriter writer = new FileWriter("samsunggalaxy.txt");
for(String str: list) {
writer.write(str);
}
writer.close();
}
}
And this is the JSON Parser line of which the error trace shows:
private void parseForTweets(){
Scanner in = null;
try {
in = new Scanner(json);
} catch (FileNotFoundException e) {
}
**Line47** while(in.hasNextLine()){
String rawTweet = in.nextLine();
if(!rawTweet.contains("\"retweeted\":true")){
Tweet tweet = TweetParser.parseTweet(rawTweet);
tweets.add(tweet);
}
}
}
I think the error is in the line String rawTweet = in.nextLine();
However I cant seem to figure this out.
Is the JSON data itself has any influence on this? I mean is it because I parsed the data wrongly? Or is it because of another reason?
Any help would be really appreciated
It seems that the problem is that you're not handling the exception, therefore, if the new Scanner(json) line failed, the in reference would be null. In such a case, you'd fail in the while(in.hasNextLine()) line.
However, without line numbers in the code it's hard to tell exactly if that's really the problem.
if you are sure the problem is in.nextLine() ( please debug your code to be sure where is the problem)
then try this one :
Iterator<JSONObject> iterator = yourJsonObject.iterator();
while (iterator.hasNext()) {
JSONObject factObj = (JSONObject) iterator.next();
...
}

ECHONEST api 4 NULL pointer exception

Below is my code, I'm not understanding the cause of the "ECHONEST api 4 NULL pointer exception":
package com.main;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.echonest.api.v4.EchoNestAPI;
import com.echonest.api.v4.EchoNestException;
import com.echonest.api.v4.Track;
import com.echonest.api.v4.TrackAnalysis;
public class SongAnalysis {
private static final String API_KEY = "14CPBOK0IFN0HRC0R";
public String getTempo(String fileName){
return null;
}
public static void main (String [] args)throws EchoNestException, IOException{
EchoNestAPI echoNest = new EchoNestAPI(API_KEY);
File file = new File("C:\\Users\\wooh\\workspace\\SongAnalysis\\songs\\b.mp3");
Track track = echoNest.uploadTrack(file,false );
track.waitForAnalysis(30000);
TrackAnalysis a = track.getAnalysis();
System.out.println("Tempo" + a.getTempo());
}
}
The likely occurrences of your NPE are:
echoNest is null.
track is null.
a is null.
You would want to pinpoint the specific location that your NullPointerException occurs, then ensure that when you instantiate the object, the object you need is being returned.

Categories

Resources