Japanese characters are not getting displayed correctly using fileChannel - java

I have a xml file which has got some Japanese characters inside it. but when i am reading the files it is getting converted to some other characters.Please see the code below :-
Customer.java
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement
public class Customer {
#Override
public String toString() {
return "Customer [name=" + name + ", age=" + age + ", id=" + id + "]";
}
String name;
int age;
int id;
public String getName() {
return name;
}
#XmlElement
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
#XmlElement
public void setAge(int age) {
this.age = age;
}
public int getId() {
return id;
}
#XmlAttribute
public void setId(int id) {
this.id = id;
}
}
Conversion.java
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Conversion {
public static void main(String[] args)
throws Exception {
Conversion conversion=new Conversion();
Path path = Paths.get("C:\\file.xml");
conversion.doReadFileNew(path);
}
private static void doReadFileNew(Path fileLocation) throws IOException, FileNotFoundException {
final int READ_FILE_BUFFER_SIZE = Integer
.valueOf(System.getProperty("READ_FILE_BUFFER_SIZE", "8192"));
StringBuilder output = null;
try (RandomAccessFile raf = new RandomAccessFile(fileLocation.toFile(), "r");
FileChannel fc = raf.getChannel();) {
output = new StringBuilder(READ_FILE_BUFFER_SIZE);
try {
ByteBuffer buffer = ByteBuffer.allocate(READ_FILE_BUFFER_SIZE);
while (fc.read(buffer) > 0) {
buffer.flip();
for (int i = 0; i < buffer.limit(); i++) {
output.append((char)buffer.get());
}
buffer.clear();
}
} finally { }
} catch (Exception e) {
throw e;
}
System.out.println(output);
}
}
The Input file "file.xml" is :-
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<customer id="100">
<age>29</age>
<name>株式会社三菱東京UFJ銀行</name>
</customer>
The OutPut is :-
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<customer id="100">
<age>29</age>
<name>₩ᅠᆰ¥ᄐマ¦ᄐレ￧ᄂᄒ¦ᄌノ│マᄆ₩ンᄆ¦ᄎᆲUFJ←ハタ│ᄀフ</name>
</customer>
Please help .

You may have to add Charset.forName("UTF-8").decode(buffer):
private static void doReadFileNew(Path fileLocation) throws IOException, FileNotFoundException {
final int READ_FILE_BUFFER_SIZE = Integer
.valueOf(System.getProperty("READ_FILE_BUFFER_SIZE", "8192"));
StringBuilder output = null;
Charset charset = Charset.forName("UTF-8");
try (RandomAccessFile raf = new RandomAccessFile(fileLocation.toFile(), "r");
FileChannel fc = raf.getChannel();) {
output = new StringBuilder(READ_FILE_BUFFER_SIZE);
try {
ByteBuffer buffer = ByteBuffer.allocate(READ_FILE_BUFFER_SIZE);
while (fc.read(buffer) > 0) {
buffer.flip();
for (int i = 0; i < buffer.limit(); i++) {
output.append(charset.decode(buffer));
}
buffer.clear();
}
} finally { }
} catch (Exception e) {
throw e;
}
System.out.println(output);
}

Try this.
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class Conversion {
public static void main(String[] args) throws Exception {
doReadFileNew("C:\\file.xml");
}
private static void doReadFileNew(String path) throws FileNotFoundException, IOException {
BufferedReader in = new BufferedReader(new FileReader(path));
String line;
while((line = in.readLine()) != null)
{
System.out.println(line);
}
in.close();
}
}

Related

Minecraft plugin hanging on "Enabling plugin" and producing out of memory errors

Why would this code be having memory issues? It runs fine once, and then when I try to run it again it hangs on "Enabling plugin". It'll then give me an OutOfMemoryException such as
"Exception: java.lang.OutOfMemoryError thrown from the UncaughtExceptionHandler in thread "Worker-Main-10""
The code I am using is as follows from the Spigot API
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.entity.Bat;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitScheduler;
import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.UUID;
public class COVID19 extends JavaPlugin {
private static ArrayList<CovidInfection> infections;
#Override
public void onEnable() {
infections = new ArrayList<CovidInfection>();
System.out.println("1");
try {
readInfections();
} catch (FileNotFoundException fnfe) {
fnfe.printStackTrace();
}
System.out.println("2");
this.getCommand("getInfected").setExecutor(new CommandGetInfected());
BukkitScheduler scheduler = getServer().getScheduler();
scheduler.scheduleSyncRepeatingTask(this, new Runnable() {
#Override
public void run() {
batCovid();
}
}, 0, 10);
System.out.println(4);
}
#Override
public void onDisable() {
try {
writeInfections();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
public void batCovid() {
System.out.println(3);
for(Player player : Bukkit.getOnlinePlayers()) {
for(Entity nearby : player.getNearbyEntities(6, 6, 6)) {
if (nearby instanceof Bat) {
String name = player.getName();
UUID uuid = player.getUniqueId();
infections.add(new CovidInfection(uuid, name, 14));
}
}
}
}
public void readInfections() throws FileNotFoundException {
File file = new File("infected.txt");
if(file.length() == 0) {
return;
}
Scanner input = new Scanner(file);
String line = input.nextLine();
while (!(line.equals(""))) {
infections.add(parseInfectionLine(line));
}
input.close();
}
public void writeInfections() throws IOException {
//File will be written as UUID,Name,DaysRemaining
FileWriter writer = new FileWriter("infected.txt", false);
for(CovidInfection infection : infections) {
writer.write(infection.toString());
}
writer.close();
}
private CovidInfection parseInfectionLine(String line) {
String[] words = line.replace("\n","").split(",");
return new CovidInfection(UUID.fromString(words[0]), words[1], Integer.parseInt(words[2]));
}
public static String getInfected() {
String compiled = "";
for (CovidInfection infection : infections) {
compiled += infection.toString() + "\n";
}
return compiled;
}
}
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class CommandGetInfected implements CommandExecutor {
#Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
String message = COVID19.getInfected();
if(!(message.equals(""))) {
sender.sendMessage(message);
} else {
sender.sendMessage("There are no infected!");
}
return(true);
}
}
import java.util.UUID;
public class CovidInfection {
private UUID uuid;
private String name;
private int days;
public CovidInfection(UUID uuid, String name, int days) {
this.uuid = uuid;
this.name = name;
this.days = days;
}
public int getDays() {
return days;
}
public String getName() {
return name;
}
public UUID getUuid() {
return uuid;
}
public void newDay() {
days--;
}
public String toString() {
return uuid.toString() + "," + name + "," + days + "\n";
}
}
Any help would be greatly appreciated, thank you!
Firstly, you are make I/O request on main thread.
To fix this issue, use multithreading such as explained here or here
Then, this :
Scanner input = new Scanner(file);
String line = input.nextLine();
Can't be used in a server.
An input like that already exist, it's the console sender.
To do that, I suggest you to use ServerCommandEvent and use spigot's console.

Unable to retrieve complete text from an element using JAXB

I am trying to retrieve text in using unmarshalling example of JAXB but unable to retrieve the within ... tag. This is my first question and hence quite unsure on indenting my code, but here it goes :
LangFlag.java
package IDJAXBParser;
import java.util.List;
import javax.xml.bind.annotation.XmlAnyElement;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
#XmlType( propOrder = { "name", "description", "match", "context" } )
#XmlRootElement( name = "langFlag" )
public class LangFlag
{
String name;
public String getName()
{
return name;
}
#XmlAttribute( name = "name" )
public void setName( String name )
{
this.name = name;
}
String description;
public String getDescription()
{
return description;
}
#XmlElement( name = "description" )
public void setDescription( String description )
{
this.description = description;
}
String context;
#XmlAnyElement(BioHandler.class)
public String getContext()
{
return context;
}
public void setContext( String context )
{
this.context = context;
}
List<String> match;
public List<String> getMatch()
{
return match;
}
#XmlElement( name = "match" )
public void setMatch( List<String> match )
{
this.match = match;
}
#Override
public String toString()
{
StringBuffer str = new StringBuffer( "Name: " + getName() + "\n" );
str.append("Description:" + getDescription() + "\n");
str.append("Context:" + getContext() + "\n");
str.append("Match:" + getMatch() + "\n");
str.append("\n");
return str.toString();
}
}
ListOfLangFlags.java
package IDJAXBParser;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement( name = "listOfLangFlags" )
public class ListOfLangFlags
{
List<LangFlag> listOfLangFlags;
public List<LangFlag> getLangFlags()
{
return listOfLangFlags;
}
/**
* element that is going to be marshaled in the xml
*/
#XmlElement( name = "langFlag" )
public void setLangFlags( List<LangFlag> listOfLangFlags )
{
this.listOfLangFlags = listOfLangFlags;
}
public void add( LangFlag langFlag )
{
if( this.listOfLangFlags == null )
{
this.listOfLangFlags = new ArrayList<LangFlag>();
}
this.listOfLangFlags.add( langFlag );
}
#Override
public String toString()
{
StringBuffer str = new StringBuffer();
for( LangFlag langFlag : this.listOfLangFlags )
{
str.append( langFlag.toString() );
}
return str.toString();
}
}
UnMarshalJAXVBComplete.java
package IDJAXBParser;
import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import IDJAXBParser.ListOfLangFlags;
public class UnMarshalJAXVBComplete
{
public static void main( String[] args )
{
try
{
File file = new File( "testv1.xml" );
JAXBContext jaxbContext = JAXBContext.newInstance( ListOfLangFlags.class );
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
ListOfLangFlags langFlags = (ListOfLangFlags)jaxbUnmarshaller.unmarshal( file );
System.out.println( langFlags );
}
catch( JAXBException e )
{
e.printStackTrace();
}
}
}
This is my XML document :
<listOfLangFlags>
<langFlag name="Lang Flag Name">
<description>Lang Flag Description</description>
<context begin="0" end="100">I am so <span class="locality">blue </span>
I'm greener than purple. </context>
<suggestions/>
<match>I am so</match>
<match>blue</match>
</langFlag>
</listOfLangFlags>
BioHandler.java
package IDJAXBParser;
import java.io.StringReader;
import java.io.StringWriter;
import javax.xml.bind.ValidationEventHandler;
import javax.xml.bind.annotation.DomHandler;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
public class BioHandler implements DomHandler<String, StreamResult> {
private static final String BIO_START_TAG = "<context>";
private static final String BIO_END_TAG = "</context>";
private StringWriter xmlWriter = new StringWriter();
public StreamResult createUnmarshaller(ValidationEventHandler errorHandler) {
xmlWriter.getBuffer().setLength(0);
return new StreamResult(xmlWriter);
}
public String getElement(StreamResult rt) {
String xml = rt.getWriter().toString();
int beginIndex = xml.indexOf(BIO_START_TAG) + BIO_START_TAG.length();
int endIndex = xml.indexOf(BIO_END_TAG);
return xml.substring(beginIndex, endIndex);
}
public Source marshal(String n, ValidationEventHandler errorHandler) {
try {
String xml = BIO_START_TAG + n.trim() + BIO_END_TAG;
StringReader xmlReader = new StringReader(xml);
return new StreamSource(xmlReader);
} catch(Exception e) {
throw new RuntimeException(e);
}
}
}
Any help would be appreciated! Thanks in advance
Here is a DomHandler implementation which convert between DOM object and String.
import java.io.StringReader;
import javax.xml.bind.ValidationEventHandler;
import javax.xml.bind.annotation.DomHandler;
import javax.xml.transform.Source;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.stream.StreamSource;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.DocumentFragment;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class BioHandler implements DomHandler<String, DOMResult> {
private StringBuilder buffer = new StringBuilder();
public DOMResult createUnmarshaller(ValidationEventHandler errorHandler) {
return new DOMResult();
}
public String getElement(DOMResult rt) {
Node n = rt.getNode();
Element ele = null;
if (n instanceof Document) {
ele = ((Document)n).getDocumentElement();
} else if (n instanceof DocumentFragment) {
ele = (Element)n.getChildNodes().item(0);
}
//StringBuilder sb = new StringBuilder(); //only capture the text under current node.
if (ele != null && "context".equals(ele.getLocalName())) {
try {
NodeList nl = (NodeList)XPathFactory.newInstance().newXPath()
.compile("descendant::text()").evaluate(ele, XPathConstants.NODESET);
int length = nl.getLength();
for (int i = 0; i < length; i++) {
buffer.append(nl.item(i).getTextContent());
}
} catch (XPathExpressionException e) {
throw new RuntimeException(e);
}
}
//for problem tracing
//System.err.println("BioHandler.getElement(), ele="+ele.getLocalName() +", result=["+result+"]");
return buffer.toString();
}
public Source marshal(String n, ValidationEventHandler errorHandler) {
try {
String xml = "<context>" + n.trim() + "</context>";
StringReader xmlReader = new StringReader(xml);
return new StreamSource(xmlReader);
} catch(Exception e) {
throw new RuntimeException(e);
}
}
}
During my testing, the unknown <suggestions/> element is handled by the same object. So I declare buffer as class variable and output captured content every time.

I want to create a text file with name coming from user and the write in it?

I wrote this program for my uni Assignment. The main idea is when ever the addItem is invoked it creates a text file and write order from the user on that file. But how ever it only creates the file but prints nothing on the inside.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
public class OrderedFood extends Food {
private int quantity;
private boolean isSet;
private SetDrink setDrink;
public OrderedFood(){
quantity = 0;
isSet = false;
setDrink = null;
}
public OrderedFood(String foodCode, String foodName,boolean isSet, SetDrink setDrink, int quantity){
super(foodCode, foodName);
this.isSet = isSet;
this.quantity = quantity;
this.setDrink = setDrink;
}
public int getquantity(){
return quantity;
}
public void setquantity(int quantity){
this.quantity = quantity;
}
public boolean getIsSet(){
return isSet;
}
public void setisSet(boolean isSet){
this.isSet = isSet;
}
public SetDrink getsetDrink(){
return setDrink;
}
public void setsetDrink(SetDrink setDrink){
this.setDrink = setDrink;
}
public void addItem (String foodCode, int TabNum)throws IOException{
clearScreen(); // invoking the clearScreen method
String filename = Integer.toString(TabNum);
try
{
//this blocks creates a table by the table num
File file = new File("/tmp", filename);
System.out.println("path=" + file.getAbsolutePath());
file.createNewFile();
System.out.println("File created");
}
catch(Exception e)
{
e.printStackTrace();
System.out.println("Failed to create file");
}
try (Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filename), "utf-8")))
{
writer.write("foodCode"); // this syntax prints the order
writer.close();
}
}
public void deleteItem(String foodCode , int TabNum)throws IOException{
clearScreen();
String Tab = Integer.toString(TabNum);
remove(Tab,foodCode);// we just invoke the remove method, which will then remove the item from the .txt file
}
public static void clearScreen() { // this method clears the screen.
System.out.print("\033[H\033[2J");
System.out.flush();
}
public void remove(String file, String lineToRemove)throws IOException {
try {
File inFile = new File(file);
if (!inFile.isFile()) {
System.out.println("Parameter is not an existing file");
return;
}
File tempFile = new File(inFile.getAbsolutePath() + ".tmp");
BufferedReader buff = new BufferedReader(new FileReader(file));
PrintWriter kap = new PrintWriter(new FileWriter(tempFile));
String line = null;
while ((line = buff.readLine()) != null) {
if (!line.trim().equals(lineToRemove)) {
kap.println(line);
kap.flush();
}
}
kap.close();
buff.close();
if (!inFile.delete()) {
System.out.println("Could not delete file");
return;
}
if (!tempFile.renameTo(inFile))
System.out.println("Could not rename file");
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
There is a logical mistake when you are creating a file you are not telling the extension also when opening the file for writing you used filename but it contains only the tabnumber not the full path to file use the below code
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
public class OrderedFood extends Food {
private int quantity;
private boolean isSet;
private SetDrink setDrink;
public OrderedFood(){
quantity = 0;
isSet = false;
setDrink = null;
}
public OrderedFood(String foodCode, String foodName,boolean isSet, SetDrink setDrink, int quantity){
super(foodCode, foodName);
this.isSet = isSet;
this.quantity = quantity;
this.setDrink = setDrink;
}
public int getquantity(){
return quantity;
}
public void setquantity(int quantity){
this.quantity = quantity;
}
public boolean getIsSet(){
return isSet;
}
public void setisSet(boolean isSet){
this.isSet = isSet;
}
public SetDrink getsetDrink(){
return setDrink;
}
public void setsetDrink(SetDrink setDrink){
this.setDrink = setDrink;
}
public void addItem (String foodCode, int TabNum)throws IOException{
clearScreen(); // invoking the clearScreen method
String filename = Integer.toString(TabNum);
try
{
//this blocks creates a table by the table num
File file = new File("/tmp", filename);
System.out.println("path=" + file.getAbsolutePath());
file.createNewFile();
filename = file.getAbsolutePath(); //here the actual address is updated to use later
System.out.println("File created");
}
catch(Exception e)
{
e.printStackTrace();
System.out.println("Failed to create file");
}
try
{
//now here we need that address updated earlier not just the tabnumber
PrintWriter writer = new PrintWriter(filename, "UTF-8");
writer.print("food code");
riter.close();
}
}
public void deleteItem(String foodCode , int TabNum)throws IOException{
clearScreen();
String Tab = Integer.toString(TabNum);
remove(Tab,foodCode);// we just invoke the remove method, which will then remove the item from the .txt file
}
public static void clearScreen() { // this method clears the screen.
System.out.print("\033[H\033[2J");
System.out.flush();
}
public void remove(String file, String lineToRemove)throws IOException {
try {
File inFile = new File(file);
if (!inFile.isFile()) {
System.out.println("Parameter is not an existing file");
return;
}
File tempFile = new File(inFile.getAbsolutePath() + ".tmp");
BufferedReader buff = new BufferedReader(new FileReader(file));
PrintWriter kap = new PrintWriter(new FileWriter(tempFile));
String line = null;
while ((line = buff.readLine()) != null) {
if (!line.trim().equals(lineToRemove)) {
kap.println(line);
kap.flush();
}
}
kap.close();
buff.close();
if (!inFile.delete()) {
System.out.println("Could not delete file");
return;
}
if (!tempFile.renameTo(inFile))
System.out.println("Could not rename file");
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}

Extracting links of a facebook page

How can I extract all the links of a facebook page. Can I extract it using jsoup and pass "like" link as parameter to extract all the user's info who liked that particular page
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 readurl(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 main(String[] args) throws IOException,
JSONException, FacebookException
{
try
{
System.out.println("\nEnter the search string:");
#SuppressWarnings("resource")
Scanner sc=new Scanner(System.in);
String s=sc.nextLine();
JSONObject json = readurl("https://graph.facebook.com/"+s);
System.out.println(json);
}}
CAN i MODIFY THIS AND INTEGRATE THIS CODE. BELOW CODE EXTRACTS ALL LINKS OF A PARTICULAR PAGE. i TRIED TO THE ABOVE CODE BUT IT'S NOT WORKING
String url = "http://www.firstpost.com/tag/crime-in-india";
Document doc = Jsoup.connect(url).get();
Elements links = doc.getElementsByTag("a");
System.out.println(links.size());
for (Element link : links)
{
System.out.println(link.absUrl("href") +trim(link.text(), 35));
}
}
public static String trim(String s, int width) {
if (s.length() > width)
return s.substring(0, width-1) + ".";
else
return s;
}
}
you can try alternative way also like this :
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.LinkedHashSet;
import java.util.Set;
import javax.swing.text.MutableAttributeSet;
import javax.swing.text.html.HTML;
import javax.swing.text.html.HTML.Tag;
import javax.swing.text.html.HTMLEditorKit;
import javax.swing.text.html.parser.ParserDelegator;
public class URLExtractor {
private static class HTMLPaserCallBack extends HTMLEditorKit.ParserCallback {
private Set<String> urls;
public HTMLPaserCallBack() {
urls = new LinkedHashSet<String>();
}
public Set<String> getUrls() {
return urls;
}
#Override
public void handleSimpleTag(Tag t, MutableAttributeSet a, int pos) {
handleTag(t, a, pos);
}
#Override
public void handleStartTag(Tag t, MutableAttributeSet a, int pos) {
handleTag(t, a, pos);
}
private void handleTag(Tag t, MutableAttributeSet a, int pos) {
if (t == Tag.A) {
Object href = a.getAttribute(HTML.Attribute.HREF);
if (href != null) {
String url = href.toString();
if (!urls.contains(url)) {
urls.add(url);
}
}
}
}
}
public static void main(String[] args) throws IOException {
InputStream is = null;
try {
String u = "https://www.facebook.com/";
URL url = new URL(u);
is = url.openStream(); // throws an IOException
HTMLPaserCallBack cb = new HTMLPaserCallBack();
new ParserDelegator().parse(new BufferedReader(new InputStreamReader(is)), cb, true);
for (String aUrl : cb.getUrls()) {
System.out.println("Found URL: " + aUrl);
}
} catch (MalformedURLException mue) {
mue.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {
is.close();
} catch (IOException ioe) {
// nothing to see here
}
}
}
}
Kind of works, but im not sure you could use jsoup for this I would rather look into casperjs or phantomjs
import java.io.IOException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class getFaceBookLinks {
public static Elements getElementsByTag_then_FilterBySelector (String tag, String httplink, String selector){
Document doc = null;
try {
doc = Jsoup.connect(httplink).get();
} catch (IOException e) {
e.printStackTrace();
}
Elements links = doc.getElementsByTag(tag);
return links.select(selector);
}
//Test functionality
public static void main(String[] args){
// The class name for the like links on facebook is UFILikeLink
Elements likeLinks = getElementsByTag_then_FilterBySelector("a", "http://www.facebook.com", ".UFILikeLink");
System.out.println(likeLinks);
}
}

java.io.IOException: Premature EOF while reading serialized object

I am working on a homework which i have to send back and forth an object in serialized mode.I have a Client3.java file which sends an object to Server3.java.And Server3.java do the exact same thing.But when i try to read the object in Client3 he throws a java.io.IOException: Premature EOF error.From an extensive search i found that my program runs faster than the InputStream reading but i dont know how to fix this
here my 2 files
package server3;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.net.HttpURLConnection;
import java.net.URL;
public class Client3 {
public static void main(String[] args) throws Exception {
try {
URL url = new URL("http://localhost:3333");
HttpURLConnection s = (HttpURLConnection) url.openConnection();
s.setDoOutput(true);
s.setDoInput(true);
s.setRequestMethod("POST");
s.setUseCaches(false);
//here we send an serialized object
Send obj = new Send();
ObjectOutputStream objOut = new
ObjectOutputStream(s.getOutputStream());
objOut.writeObject(obj);
/*********this is the chunk of code that makes the error*****************/
//here we read the serialized object
InputStream in = s.getInputStream();
ObjectInputStream ios = new ObjectInputStream(in);
SendResponse oin = (SendResponse) ios.readObject();
String gabim=oin.getGabim();
String gabimNr =oin.getGabimNr();
System.out.println(gabim);
System.out.println(gabimNr);
ios.close();
s.disconnect();
/***************************************************************************/
//catch all the possible errors
} catch (IOException ex) {
System.err.println("Gabim ne klient"+ex);
ex.printStackTrace();
}
}
}
class Send implements Serializable {
// the object to be send to the server
private static final long serialVersionUID = 1L;
int id = 1;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getAmount() {
return amount;
}
public void setAmount(int amount) {
this.amount = amount;
}
public int getPaid() {
return paid;
}
public void setPaid(int paid) {
this.paid = paid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
int amount = 2000;
int paid = 800;
String name = "Andi Domi";
}
And here it is the Server3.java file
package server3;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.net.InetSocketAddress;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
public class Server3 {
public static void main(String[] args) throws Exception {
//create the server
HttpServer server = HttpServer.create(new InetSocketAddress(3333), 0);
server.createContext("/", new MyHandler());
server.setExecutor(null); // creates a default executor
server.start();
}
static class MyHandler implements HttpHandler {
public void handle(HttpExchange t) throws IOException {
/*******we start to read the object send from the client here*******/
//create the sream
ObjectInputStream ios = new ObjectInputStream(t.getRequestBody());
//variables we need to connect to the database
final String url = "jdbc:mysql://localhost/httpServer";
final String user = "root";
final String password = "";
try {
//create the object to be read
Send oin = (Send) ios.readObject();
int id = oin.getId();
String emri = oin.getName();
int amount = oin.getAmount();
int paid = oin.getPaid();
//jdbc try
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(url, user,password);
//insert values into the first table
PreparedStatement s = con
.prepareStatement("INSERT INTO person(ID,Name,Amount,Paid) VALUES (?,?,?,?)");
s.setInt(1, id);
s.setString(2, emri);
s.setInt(3, amount);
s.setInt(4, paid);
s.executeUpdate();
//read the values from a table and add them to an array list
ResultSet rs = s.executeQuery("SELECT * from personat ORDER BY ID");
ArrayList<Personat> perList = new ArrayList<Personat>();
if (rs != null) {
while (rs.next()) {
Personat per = new Personat();
per.setID(rs.getInt("ID"));
per.setName(rs.getString("Name"));
per.setAmount(rs.getInt("Amount"));
perList.add(per);
}
}
//send the serialized object
String gabim="Ska asnje gabim";
String gabimNr="1";
t.sendResponseHeaders(200,0);
OutputStream os = t.getResponseBody();
SendResponse obj = new SendResponse(gabim,gabimNr,perList);
ObjectOutputStream objOut = new ObjectOutputStream(os);
objOut.writeObject(obj);
objOut.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
//ketu cojme nje object me keto te dhena
String gabim=("Dicka nuk shkoi mire me marrjen e objektit");
String gabimNr="3";
rrayList<Personat> perList = null;
t.sendResponseHeaders(200,0);
OutputStream os = t.getResponseBody();
SendResponse obj = new SendResponse(gabim,gabimNr,perList);
ObjectOutputStream objOut = new ObjectOutputStream(os);
objOut.writeObject(obj);
objOut.close();
} catch (SQLException e) {
//ketu cojme nje objekt me keto te dhena
e.printStackTrace();
String gabim=("Dicka nuk shkoi mire ne lidhje me databasin");
String gabimNr="4";
ArrayList<Personat> perList = null;
t.sendResponseHeaders(200,0);
OutputStream os = t.getResponseBody();
SendResponse obj = new SendResponse(gabim,gabimNr,perList);
ObjectOutputStream objOut = new ObjectOutputStream(os);
objOut.writeObject(obj);
objOut.close();
}
}
}
}
class Personat {
int ID;
String Name;
int Amount;
public int getID() {
return ID;
}
public void setID(int iD) {
ID = iD;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public int getAmount() {
return Amount;
}
public void setAmount(int amount) {
Amount = amount;
}
}
class SendResponse implements Serializable {
private static final long serialVersionUID = 1L;
String gabim;
String gabimNr;
ArrayList<Personat> personList;
public SendResponse(String gabim, String gabimNr,
ArrayList<Personat> personList) {
super();
this.gabim = gabim;
this.gabimNr = gabimNr;
this.personList = personList;
}
public String getGabim() {
return gabim;
}
public void setGabim(String gabim) {
this.gabim = gabim;
}
public String getGabimNr() {
return gabimNr;
}
public void setGabimNr(String gabimNr) {
this.gabimNr = gabimNr;
}
public ArrayList<Personat> getPersonList() {
return personList;
}
public void setPersonList(ArrayList<Personat> personList) {
this.personList = personList;
}
}
after i run it from the ex.printStackTrace(); in the Client3 file i get this :
java.io.IOException: Premature EOF
java.io.IOException: Premature EOF
at sun.net.www.http.ChunkedInputStream.readAheadBlocking(Unknown Source)
at sun.net.www.http.ChunkedInputStream.readAhead(Unknown Source)
at sun.net.www.http.ChunkedInputStream.read(Unknown Source)
at java.io.FilterInputStream.read(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection$HttpInputStream.read(Unknown Source)
at java.io.ObjectInputStream$PeekInputStream.read(Unknown Source)
at java.io.ObjectInputStream$PeekInputStream.readFully(Unknown Source)
at java.io.ObjectInputStream$BlockDataInputStream.readShort(Unknown Source)
at java.io.ObjectInputStream.readStreamHeader(Unknown Source)
at java.io.ObjectInputStream.<init>(Unknown Source)
at server3.Client3.main(Client3.java:29)
i dont know hot to read the file faster or make my program slower ,do someone have any idea ?
I don't think it's due to the speed of your program, I would expect readObject() to block if there wasn't anything to read. Instead I think you are missing a terminator in the data you are trying to read, you need to take a look at the data that is being sent to your program. A similar issue was resolved here, though it is using readLine()

Categories

Resources