I get an Error when using InputSource
for XPath
.
InputSource inputSource = null;
try {
inputSource = new InputSource(new FileInputStream(filename));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String s = readFromFile(filename);
String uuid = taskItems.get(position).get("uuid");
XPath xPath = XPathFactory.newInstance().newXPath();
try {
Node taskNode = (Node) xPath.evaluate("//task[@uuid='" + uuid + "']", inputSource, XPathConstants.NODE);
Document document = taskNode.getOwnerDocument();
//Füge neue Zeile ein
Node noteNode = document.createElement("task_note");
noteNode.setTextContent(taskItems.get(position).get("task_note"));
taskNode.appendChild(noteNode);
//Speichere Datei
Source input = new DOMSource(document);
Result output = new StreamResult(new File(filename));
TransformerFactory.newInstance().newTransformer().transform(input, output);
} catch (XPathExpressionException e) {
e.printStackTrace();
} catch (TransformerException e) {
e.printStackTrace();
}
I don't know why but when using String s = readFromFile(filename);', I get the File inside
String s`.
readFromFile:
private String readFromFile(String fileName) {
String ret = "";
String UTF8 = "UTF-8";
int BUFFER_SIZE = 8192;
try {
InputStream inputStream = openFileInput(fileName);
if (inputStream != null) {
BufferedReader bufferedReader1 = new BufferedReader(new InputStreamReader(inputStream, UTF8), BUFFER_SIZE);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ((receiveString = bufferedReader1.readLine()) != null) {
stringBuilder.append(receiveString);
}
inputStream.close();
ret = stringBuilder.toString();
}
} catch (FileNotFoundException e) {
Log.e("readFromFile: ", "Datei nicht gefunden: " + e.toString());
e.printStackTrace();
} catch (IOException e) {
Log.e("readFromFile: ", "Kann Datei nicht lesen: " + e.toString());
e.printStackTrace();
}
return ret;
}
writeToFile:
private void writeToFile(String data, String fileName) {
try {
String UTF8 = "UTF-8";
int BUFFER_SIZE = 8192;
FileOutputStream fileOutputStream = openFileOutput(fileName, Context.MODE_PRIVATE);
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(fileOutputStream, UTF8), BUFFER_SIZE);
bufferedWriter.write(data);
bufferedWriter.close();
} catch (IOException e) {
Log.e("writeToFile: ", "Datei-Erstellung fehlgeschlagen: " + e.toString());
}
}
So what do I have to change, to make InputSource find the File?
In readFromFile
you're calling openFileInput
, instead of the FileInputStream
constructor. So do the same thing when you want to create an InputSource
:
inputSource = new InputSource(openFileInput(filename));
See more on this question at Stackoverflow