How to search and remove some values from xml java - java

I have an xml abc.xml
<soapenv:Envelope>
<soapenv:Header/>
<soapenv:Body>
<mes:SomeRq>
<RqID>?</RqID>
<MsgRqHdr>
....
</mes:SomeRq>
</soapenv:Body>
</soapenv:Envelope>
Is there a way i can search mes:, from this xml and replace it with ins:
Thanks in advance.
public static void findreplcae(String strFilePath) throws IOException {
String currentString = "mes:";
String changedString = "ins:";
BufferedReader reader = new BufferedReader(new FileReader(strFilePath));
StringBuffer currentLine = new StringBuffer();
String currentLineIn;
while ((currentLineIn = reader.readLine()) != null) {
System.out.println(currentLineIn);
boolean bool = false;
String trimmedLine = currentLineIn.trim();
System.out.println(trimmedLine);
if (trimmedLine.contains(currentString)) {
trimmedLine.replace(currentString, changedString);
bool = true;
if (bool != true) {
currentLine = currentLine.append(currentLineIn + System.getProperty("line.separator"));
}
}
reader.close();
BufferedWriter writer = new BufferedWriter(new FileWriter(strFilePath));
writer.write(currentLine.toString());
writer.close();
}
}

It's not good idea to parse it as a text file. DocumentBuilder.parse to parse the file, call getDocumentElement() and check for getPrefix. If it matches, replace with setPrefix(). Note you have to register prefix if not yet done already.
Check this page for tutorial.

Some issues:
trimmedLine.replace(currentString, changedString);, the result is returned, so you have to store it somewhere. See here
What is this supposed to do?
bool = true;
if (bool != true) {
currentLine = currentLine.append(currentLineIn + System.getProperty("line.separator"));
}
Don't close the reader while reading in a loop.
If you want to overwrite the original file, this should do (although I am not sure, if you really want to trim the lines):
String currentString = "mes:";
String changedString = "ins:";
try {
BufferedReader reader = new BufferedReader(new FileReader(strFilePath));
StringBuffer newContents = new StringBuffer();
String currentLineIn = null;
while ((currentLineIn = reader.readLine()) != null) {
String trimmedLine = currentLineIn.trim();
if (trimmedLine.contains(currentString)) {
newContents.append(trimmedLine.replace(currentString, changedString));
}
else {
newContents.append(trimmedLine);
}
newContents.append(System.getProperty("line.separator"));
}
reader.close();
BufferedWriter writer = new BufferedWriter(new FileWriter(strFilePath));
writer.write(newContents.toString());
writer.close();
} catch (IOException e) {
// TODO handle it
}

Related

How to append multiple text in text file

I want the results from 'name' and 'code' to be inserted into log.txt file, but if I run this program only the name results gets inserted into .txt file, I cannot see code results appending under name. If I do System.outprintln(name) & System.outprintln(code) I get results printed in console but its not being inserted in a file.Can someone tell me what am I doing wrong?
Scanner sc = new Scanner(file, "UTF-8");
BufferedReader br = new BufferedReader(new FileReader(file));
PrintWriter out = new PrintWriter(new FileWriter("log.txt", true));
while ((line = br.readLine()) != null) {
if (line.contains("text1")) {
String[] splits = line.split("=");
String name = splits[2];
for (int i = 0; i < name.length(); i++) {
out.println(name);
}
}
if (line.contains("text2")) {
String[] splits = line.split("=");
String code = splits[2];
for (int i = 0; i < code.length(); i++) {
out.println(code);
}
}
out.close()
}
File looks like:
Name=111111111
Code=333,5555
Category-Warranty
Name=2222222
Code=111,22
Category-Warranty
Have a look at this code. Does that work for you?
final String NAME = "name";
final String CODE = "code";
BufferedReader br = new BufferedReader(new FileReader(file));
PrintWriter out = new PrintWriter(new FileWriter("log.txt", true));
while ((line = br.readLine()) != null) {
String[] splits = line.split("=");
String key = splits[0];
String value = splits[1];
if (key.equals(NAME) || key.equals(CODE)) {
out.println(value);
}
}
out.close();
You have a couple of problems in your code:
you never actually assign the variables name and code.
you close() your PrintWriter inside the while-loop, that means you will have a problem if you read more than one line.
I don't see why this wouldn't work, without seeing more of what you are doing:
BufferedReader br = new BufferedReader(new FileReader(file));
PrintWriter out = new PrintWriter(new FileWriter("log.txt", true));
while ((line = br.readLine()) != null) {
if (line.contains("=")) {
if (line.contains("text1")) {
String[] splits = line.split("=");
if (splits.length >= 2) {
out.println(splits[1]);
}
}
if (line.contains("text2")) {
String[] splits = line.split("=");
if (splits.length >= 2) {
out.println(splits[1]);
}
}
}
}
out.flush();
out.close();
Make sure the second if condition is satisfied i.e. the line String contains "text2".

How to extract starting of a String in Java

I have a text file with more than 20,000 lines and i need to extract specific line from it. The output of this program is completely blank file.
There are 20,000 lines in the txt file and this ISDN line keeps on repeating lots of time each with different value. My text file contains following data.
RecordType=0(MOC)
sequenceNumber=456456456
callingIMSI=73454353911
callingIMEI=85346344
callingNumber
AddInd=H45345'1
NumPlan=H34634'2
ISDN=94634564366 // Need to extract this "ISDN" line only
public String readTextFile(String fileName) {
String returnValue = "";
FileReader file = null;
String line = "";
String line2 = "";
try {
file = new FileReader(fileName);
BufferedReader reader = new BufferedReader(file);
while ((line = reader.readLine()) != null) {
// extract logic starts here
if (line.startsWith("ISDN") == true) {
System.out.println("hello");
returnValue += line + "\n";
}
}
} catch (FileNotFoundException e) {
throw new RuntimeException("File not found");
} finally {
if (file != null) {
try {
file.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return returnValue;
}
We will assume that you use Java 7, since this is 2014.
Here is a method which will return a List<String> where each element is an ISDN:
private static final Pattern ISDN = Pattern.compile("ISDN=(.*)");
// ...
public List<String> getISDNsFromFile(final String fileName)
throws IOException
{
final Path path = Paths.get(fileName);
final List<String> ret = new ArrayList<>();
Matcher m;
String line;
try (
final BufferedReader reader
= Files.newBufferedReader(path, StandardCharsets.UTF_8);
) {
while ((line = reader.readLine()) != null) {
m = ISDN.matcher(line);
if (m.matches())
ret.add(m.group(1));
}
}
return ret;
}

find specific string after certain pattern in a txt file

so i am new to java.please offer some sample codes if possible.
The situation is i have a html format in a text file. i need to read the file and find the string after a pattern which is 'data-name'. i need to find every string after the "data-name" through the entire text file. i did some research online . i already used html parser to get the html and store it in a text file. i know i might need to use regular expression. so please help me. Thank you guys!
below is my code for getting the html. the result is concatenated.
public static void main(String[] args) {
try {
URL url = new URL("https://twitter.com/search?q=%23JENOSMROOKIESOPENFOLBACK&src=tren");
// read text returned by server
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String line;
PrintWriter out = new PrintWriter(new FileWriter("C:/Users/Desktop/htmlsourcecode.txt"));
while ((line = in.readLine()) != null) {
System.out.println(line);
out.print(line);
}
out.close();
}
How about something like this
// External resource(s).
BufferedReader in = null;
PrintWriter out = null;
try {
URL url = new URL(
"https://twitter.com/search?q=%23JENOSMROOKIESOPENFOLBACK&src=tren");
// read text returned by server
in = new BufferedReader(new InputStreamReader(
url.openStream()));
String line;
// out = new PrintWriter(new FileWriter(
// "htmlsourcecode.txt"));
final String DATA_NAME = "data-name=\"";
while ((line = in.readLine()) != null) {
int pos1 = line.indexOf(DATA_NAME); // opening position.
if (pos1 > -1) { // did we match?
// Add the length of the string.
pos1 += DATA_NAME.length();
// find the closing quote.
int pos2 = line.indexOf("\"", pos1 + 1);
if (pos2 > -1) {
String dataName = line.substring(pos1,
pos2);
System.out.println(dataName);
// out.print(line);
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// Close external resource(s).
if (in != null) {
try {
in.close();
} catch (IOException e) {
}
}
if (out != null) {
out.close();
}
}

Java File cannot be deleted nor renamed

See my code below:
I can write a key and a string in one line of a file. If the key already exists I want to overwrite it by creating a new file and fill it with the content of my source file. In the end I am going to delete the old file and rename my temporary file. But it does not work. As you can see I print booleans for deleting and renameTo methods. Both are returned as "false".
I read in some other Threads that I have to close all Readers and Writers that are in contact with my file in order to be able to rename or delete it.
You see my fault?
(Note that some comments are written in german)
public static boolean dini_Set(String filepath, String key, String value) throws IOException
{
if(key.length() <= 0 || value.length() <= 0) return false;
String pfilepath = rootdirectory.concat(filepath);
File pfile = new File(pfilepath);
//dini_Remove(filepath.concat(".part"));
if(dini_Exists(filepath) == false) return false;
// Checkt ob der Key schon existiert
FileReader fr = new FileReader(pfilepath);
BufferedReader br = new BufferedReader(fr);
String ausw;
boolean foundkeybool = false;
while((ausw = br.readLine()) != null)
{
String foundkey = ausw.substring(0,ausw.indexOf("="));
//System.out.println(foundkey);
if(foundkey.equals(key))
{
foundkeybool = true;
System.out.println(foundkeybool);
// Key exists and content has to be overwritten
String newline = key.concat("=").concat(value);
String tmpdir = rootdirectory.concat("tmp.tmp");
File tmp = new File(tmpdir);
tmp.createNewFile();
String currentLine;
FileWriter fw = new FileWriter(tmpdir);
BufferedWriter bw = new BufferedWriter(fw);
br.close();
fr.close();
fr = new FileReader(pfilepath);
br = new BufferedReader(fr);
while((currentLine = br.readLine()) != null)
{
// trim newline when comparing with lineToRemove
String trimmedLine = currentLine.trim();
System.out.println(trimmedLine);
if(trimmedLine.equals(ausw))
{
System.out.println("Austauschen: "+newline);
bw.write(newline);
}
else
{
bw.write(currentLine);
System.out.println("Lassen: "+currentLine);
}
bw.newLine();
}
br.close();
fr.close();
bw.close();
fw.close();
tmp.setWritable(true);
pfile.setWritable(true);
// boolean removed = dini_Remove(filepath);
boolean removed = pfile.delete();
System.out.println("Datei wurde gelöscht: "+removed);
boolean renamed = tmp.renameTo(pfile);
System.out.println("Datei umbenannt: "+renamed);
break;
}
}
// if key does now exists we can create a new one
if(foundkeybool == false)
{
FileWriter fw = new FileWriter(pfilepath,true);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(key.concat("=").concat(value));
bw.newLine();
bw.close();
}
return true;
}
This may not fix your problem, but it will get you closer.
You MUST ensure that any resource that you open is closed properly. Currently in your code, if, for some reason, an exception is thrown, none of your resources will be closed.
Even if you're not interested in dealing with the exception within the method, you should still wrap the file access code within a try-finally block
FileReader fr = null;
BufferedReader br = null;
try {
fr = new FileReader(pfilepath);
br = new BufferedReader(fr);
//...//
} finally {
try {
br.close();
} catch (Exception exp) {
}
try {
fr.close();
} catch (Exception exp) {
}
}
You may find that you only need to close the BufferedReader and it should be calling close on it's child Reader, but I'm paranoid about ensuring that everything is clean
If you are using Java 7, you may wish to take a look at The try-with-resources Statement
Updated
I'm not sure your code makes sense. Basically, what you should be doing, is reading the entire source file and writing it the temp location (as you don't know in advance if the key needs to be updated, and you would probably need to read the source file anyway to find out).
Once this has being completed, if you made changes to the temp file, delete the source file and rename the temp file into it's place.
You code seems mighty inefficient to me...
Okai, I want to give you a brief update about the code.
I changed it this way and for now it is working as it should.
Do you have some more things I can change to optimize the code?
public static boolean dini_Set(String filepath, String key, String value) throws IOException
{
if(key.length() <= 0 || value.length() <= 0) return false;
String pfilepath = rootdirectory.concat(filepath);
File pfile = new File(pfilepath);
//dini_Remove(filepath.concat(".part"));
if(dini_Exists(filepath) == false) return false;
// Checkt ob der Key schon existiert
boolean foundkeybool = false;
File tmp = null;
try(BufferedReader br = new BufferedReader(new FileReader(pfilepath)))
{
String ausw;
while((ausw = br.readLine()) != null)
{
String foundkey = ausw.substring(0,ausw.indexOf("="));
System.out.println(foundkey);
if(foundkey.equals(key))
{
foundkeybool = true;
System.out.println(foundkeybool);
//Key exists and content has to be overwritten
String newline = key.concat("=").concat(value);
String tmpdir = rootdirectory.concat("tmp.tmp");
tmp = new File(tmpdir);
tmp.createNewFile();
String currentLine;
try(BufferedWriter bw = new BufferedWriter(new FileWriter(tmpdir)))
{
try(BufferedReader br2 = new BufferedReader(new FileReader(pfilepath)))
{
while((currentLine = br2.readLine()) != null)
{
//trim newline when comparing with lineToRemove
String trimmedLine = currentLine.trim();
System.out.println(trimmedLine);
if(trimmedLine.equals(ausw))
{
System.out.println("Austauschen: "+newline);
bw.write(newline);
}
else
{
bw.write(currentLine);
System.out.println("Lassen: "+currentLine);
}
bw.newLine();
}
}
}
break;
}
}
}
if(foundkeybool == true)
{
tmp.setWritable(true);
pfile.setWritable(true);
//boolean removed = dini_Remove(filepath);
boolean removed = pfile.delete();
System.out.println("Datei wurde gelöscht: "+removed);
boolean renamed = tmp.renameTo(pfile);
System.out.println("Datei umbenannt: "+renamed);
}
else //(foundkeybool == false) if key does now exists we can create a new one
{
try(BufferedWriter bw = new BufferedWriter(new FileWriter(pfilepath,true)))
{
bw.write(key.concat("=").concat(value));
bw.newLine();
bw.close();
}
}
return true;
}

How to read BufferedReader faster

I want to optimize this code:
InputStream is = rp.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String text = "";
String aux = "";
while ((aux = reader.readLine()) != null) {
text += aux;
}
The thing is that i don't know how to read the content of the bufferedreader and copy it in a String faster than what I have above.
I need to spend as little time as possible.
Thank you
Using string concatenation in a loop is the classic performance killer (because Strings are immutable, the entire, increasingly large String is copied for each concatenation). Do this instead:
StringBuilder builder = new StringBuilder();
String aux = "";
while ((aux = reader.readLine()) != null) {
builder.append(aux);
}
String text = builder.toString();
You can try Apache IOUtils.toString. This is what they do:
StringWriter sw = new StringWriter();
char[] buffer = new char[1024 * 4];
int n = 0;
while (-1 != (n = input.read(buffer))) {
sw.write(buffer, 0, n);
}
String text = sw.toString();
When BufferedReader reads from Socket, it is necessary to add bufferedReader.ready():
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
StringBuilder sb= new StringBuilder();
String line = "";
while (br.ready() && (line = br.readLine()) != null) {
sb.append(line + "\r\n");
}
String result = sb.toString();
One line solution:
String result = reader.lines().collect(joining(lineSeparator()));
Imports:
import java.io.*;
import static java.lang.System.lineSeparator;
import static java.util.stream.Collectors.joining;
I wrote a simple function to do this using StringBuilder and While loop with catching IOException inside.
public String getString(BufferedReader bufferedReader) {
StringBuilder stringBuilder = new StringBuilder();
String line = null;
do {
try {
if ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line).append(System.lineSeparator());
}
} catch (IOException e) {
e.printStackTrace();
}
} while (line != null);
return stringBuilder.toString();
}
You can use StringBuffer
while ((aux = reader.readLine()) != null) {
stringBuffer.append(aux);
}

Categories

Resources