Question

This also a Unix question so, here is the deal: I have a whole String variable in Java, which is the content of an XML file, and I want to write this whole text into a file with one command like:

echo "<xml>
        <data>
        </data>
     </xml>" > basic.xml

And with this kind of text, unix gives the error that

I have did it with properties files but there were no spaces in it so it did not gave me an error.

I also tried to replace the \n chars with $'\n' like:

contentStr=contentStr.replaceAll("\n", "\\$'\n'");

but JSCH gave me the unix error.

Any ideas?

Thnx

Ali

Was it helpful?

Solution 2

contentStr=contentStr.replace("\n", "\\n");
contentStr=contentStr.replace("\"", "\\\"");            

writeOperation.setCommand("printf \""+contentStr+"\" > "+source.getPath());

That s the answer. Sort of anyway;)

OTHER TIPS

The example you give for replaceAll is not quite right. You are replacing the carriage return character with a backslash, followed by a dollar, followed by singlequote, carriage return, single quote. I think you are looking to replace it with backslash, dollar, singlequote, backslash, n, singlequote? Get rid of the actual carriage return and replace it with a sort of escape sequence?

Try contentStr=contentStr.replace("\n", "$'\\n'");

The thing to bear in mind about replaceAll() is that you can get funny results if you have backslashes or dollars in the second string. From the docs: "Note that backslashes () and dollar signs ($) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string. Dollar signs may be treated as references to captured subsequences as described above, and backslashes are used to escape literal characters in the replacement string." Using replace() is a much better option here.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top