I am trying to parse xml from URL with jdom-2.0.6.jar, but i get IOException:
IOException: Couldn't open "here is xml link"
That what I am doing:
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
String myurl = "https://myfile.xml";
SAXBuilder builder = new SAXBuilder();
try {
Document document = builder.build(myurl);
Element rootNode = document.getRootElement().getChild("myroot");
} catch (IOException io) {
Log.d("IOException", io.getMessage());
} catch (JDOMException jdomex) {
Log.d("JDOMException", jdomex.getMessage());
}
The same code works well in Eclipse, but not in Android Studio. So what is wrong?
I did not have in log (android.os.NetworkOnMainThreadException) exception, but after using this solution I finally parsed xml.
Change to Log.w("IOException", io.getMessage(), io) to get the full stack trace, maybe we can identify the problem from there.
Related
I am trying to parse HTML with JSOUP library from local file. But my IDE can't find this file.
Project structure:
- ParsingHTML
- .idea
- files
- index.html
- login.html
- libs
- out
- src
- Parsing.java
Here is my code:
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import java.io.File;
import java.io.IOException;
public class Parsing {
public static void main(String[] args) {
try {
File input = new File("./../files/index.html");
Document doc = Jsoup.parse(input, "UTF-8", "https://jsoup.com/");
System.out.println(doc);
} catch (IOException e) {
e.printStackTrace();
}
}
}
How I can fix it?
P.S.:
Change directory name from file to files and file from "input" to "index".
You are getting this error because this location not exist.
Try to use:
File input = new File("files/input.html");
or
Path input = Paths.get("files","input.html");
use
final String dir = System.getProperty("user.dir");
Example:
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import java.io.File;
import java.io.IOException;
public class Parsing {
public static void main(String[] args) {
try {
final String dir = System.getProperty("user.dir");
final File input = new File(dir +"/files/input.html");
final Document doc = Jsoup.parse(input, "UTF-8", "https://jsoup.com/");
System.out.println(doc.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
}
What your project structure tells is that yours "input.html" file doesn't exist, so the error is correct. Maybe you ctrl+c ctrl+v the Jsoup example without changing the html file's name.
Also check:
new File("./../files/input.html");
In your project the folder name is file, not files.
I allready saw other questions about the same problem but i still get an error. Hier is the small part of code where i try to modify exosting xml files. But it modifies some characters in text.
import org.jdom2.Document;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
import java.io.FileOutputStream;
import java.io.IOException;
public class ModyfyXml {
public static void main(String[] args) throws JDOMException, IOException {
try {
SAXBuilder sax = new SAXBuilder();
Document doc = sax.build("F:\\c\\test.xml");
XMLOutputter xmlOutput = new XMLOutputter();
Format format = Format.getPrettyFormat();
format.setEncoding("UTF-8");
xmlOutput.setFormat(format);
xmlOutput.output(doc, (new FileOutputStream("F:\\c\\test2.xml")));
}catch (IOException io) {
io.printStackTrace();
} catch (JDOMException e) {
e.printStackTrace();
}
}}
Hier a small xml file that i try to modify (in this case just copy)
<?xml version="1.0" encoding="utf-8"?><page>
䕶法喇嘛所居此處𡸁仲無妻室亦降神附體
</page>
After program start i get the following:
<?xml version="1.0" encoding="UTF-8"?>
<page>䕶法喇嘛所居此處𡸁仲無妻室亦降神附體</page>
Some chineese characters can't be right transformed
Dang I never noticed this bug in JDOM 2.
You will have the same results with any non-BMP character. You can try with the emoji mania of these latest years and see you get the same results.
It happens because of the escape strategy automatically set for UTF-whatever encodings. What it does is rather wrong.
That will be fixed if you replace the strategy with one that doesn't escape anything beside XML reserved chars:
format.setEscapeStrategy((c) -> false);
I want to read object from Android internal storage.
The following is my code.
I write a static function for reading object from file in the same class.
No idea why this exception happen .
Really appreciate if you could give some suggestions.
thanks.
package com.crescent.programmercalculator;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import android.util.Log;
import android.content.Context;
public class CalculateConfigurations implements Serializable{
static String configLocation="configFile";
public short radix;
CalculateConfigurations(){
radix=16;
}
public static CalculateConfigurations loadObjectFromFile(Context context){
try {
FileInputStream fis = context.openFileInput(configLocation);
ObjectInputStream is = new ObjectInputStream(fis);
CalculateConfigurations config = (CalculateConfigurations) is.readObject();
is.close();
fis.close();
return config;
} catch (FileNotFoundException e) {
// first use case
Log.v("CalculateConfigurations", "first init for configuration file");
return new CalculateConfigurations();
} catch (IOException e) {
e.printStackTrace();
Log.e("CalculateConfigurations", "Fatal error, configuration file may be broken");
return new CalculateConfigurations();
}
catch (ClassNotFoundException e) {
e.printStackTrace();
Log.e("CalculateConfigurations", "Fatal error, unknown");
return new CalculateConfigurations();
}
}
}
ClassNotFoundException
this is in most cases some mixup in your xml-files. If you post both stacktrace and the proper xml-file, it is easy to fix it!
Read on readObject
Exceptions are thrown for problems with the InputStream and for
classes that should not be deserialized. All exceptions are fatal to
the InputStream and leave it in an indeterminate state; it is up to
the caller to ignore or recover the stream state.
Since you are trying to read an android internal library, it cannot be casted to your custom Class. Hence the ClassNotFoundException.
Hope this helps.
I encounter the same problem today. I don't know how the serialization/deserialization is done but I notice that it is very unstable process.
If you serialize some objects and put the memory, you cannot change the data type/class name easily.. If it throws class not found exception like this, remove the app from device and install again. I hope, it helps some developers :)
I am new to Java, have searched on the net and this forum but unable to figure out why my code is not compiling? Any help will be highly appreciated.
//filename is TestHTTPConnection.java
class TestHTTPConnection {
public static void main (String[] args){
String strUrl = "http://abc.com";
try {
URL url = new URL(strUrl);
URLConnection Conn = url.openConnection();
Conn.connect();
assertEquals(URLConnection.HTTP_OK, Conn.getResponseCode());
} catch (IOException e) {
System.err.println("Error creating HTTP connection");
e.printStackTrace();
throw e;
}
}
}
Compilation error - complains about "URL", "URLConnection" and "IOException".
You need to import those classes / interfaces !
You are missing two things:
a package line:
package yourdomain.yourapp;
and a list of imports:
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
Most java developers use an IDE which automates all of this (such as NetBeans, IntelliJ IDEA, or Eclipse)
If your not using an IDE (Eclipse , NetBeans etc.) then download one which will give you content assist and point out mistakes like this.
I have issue with using utf-8 with JDOM parser. My code won't write encoded in utf-8.
Here's code:
import java.io.FileWriter;
import java.io.IOException;
import org.jdom2.Element;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
import org.jdom2.Document;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
public class Jdom2 {
public static void main(String[] args) throws JDOMException, IOException {
String textValue = null;
try {
SAXBuilder sax = new SAXBuilder();
Document doc = sax.build("path/to/file.xml");
Element rootNode = doc.getRootElement();
Element application = rootNode.getChild("application");
Element de_DE = application.getChild("de_DE");
textValue = de_DE.getText();
System.out.println(textValue);
application.getChild("de_DE").setText(textValue);
Format format = Format.getPrettyFormat();
format.setEncoding("UTF-8");
XMLOutputter xmlOutput = new XMLOutputter(format);
xmlOutput.output(doc, new FileWriter("path/to/file.xml"));
} catch (IOException io) {
io.printStackTrace();
} catch (JDOMException e) {
e.printStackTrace();
}
}
}
So line System.out.println(textValue); prints text "Mit freundlichen Grüßen", which is exactly what is read from xml file, but when it writing down, I get "Mit freundlichen Gr����"
Here's my xml file
<?xml version="1.0" encoding="UTF-8"?>
<applications>
<application id="default">
<de_DE>Mit freundlichen Grüßen</de_DE>
</application>
</applications>
How will I achieve writing "Mit freundlichen Grüßen" instead of "Mit freundlichen Gr����" ?
Thanks in advance!
This is probably the issue:
xmlOutput.output(doc, new FileWriter("path/to/file.xml"));
FileWriter always uses the platform default encoding. If that's not UTF-8, you've got problems.
I suggest you use a FileOutputStream instead, and let JDOM do the right thing. (Also, I strongly suspect you should keep a reference to the stream so you can close it in a finally block...)
I would totally go for #Jon Skeet answer, but if the code is in the 3rd party library that you cannot modify there are two other options:
Run your JVM with additional environment variable specifying file.encoding:
java -Dfile.encoding=UTF-8 … Jdom2
You can try to modify the Charset.defaultCharset which stores encoding used by FileWritter. Keep in mind that it's a very hacky solution that might break at some point and I would avoid it at all:
Field field = null;
for (Field f : Charset.class.getDeclaredFields()) {
if (f.getName().equals("defaultCharset")) {
field = f;
}
}
field.setAccessible(true);
Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
field.set(null, StandardCharsets.UTF_8);
One last remark. Both solution might introduce side effects in other parts of your application because you are changing default encoding that might be used by some libraries.