I have tried different ways to write a string to a file.
File file = new File(eventPath)
file.withWriterAppend { it << xmlDocument }
OR
file << xmlDocument
In this way, the string when the file size reaches 1kb is interrupted.
If I do this way (as explained here: java: write to xml file)
File file = new File("foo")
if (file.exists()) {
assert file.delete()
assert file.createNewFile()
}
boolean append = true
FileWriter fileWriter = new FileWriter(file, append)
BufferedWriter buffWriter = new BufferedWriter(fileWriter)
100.times { buffWriter.write "foo" }
buffWriter.flush()
buffWriter.close()
Happens that the string gets repeated.
How can I use the first method without have limit on string size? Thanks
Does:
new File(eventPath).withWriterAppend { it.writeLine xmlDocument }
work?
Related
I created a text file with the content "Hello" and I was trying to read these characters from the file and write it back to the same file again.
Assumptions:
1. the file now has the content "Hello" (Overwritten)
2. the file now has the content "HelloHello" (Appended)
3. the file now has the content infinite "Hello" (or an exception gets thrown)
Actual result:
Original "Hello" characters gets deleted from the text file, and the file was left empty.
Actual test
#Test
public void testCopyStream() throws IOException {
File workingDir = new File(System.getProperty("user.dir"));
File testFile = new File(workingDir, "/test.txt");
FileReader fin = new FileReader(testFile);
FileWriter fos = new FileWriter(testFile);
copyStream(fin, fos);
fin.close();
fos.close();
}
I have created the following method for "copying" the data in the InputStream to the OutputStream:
private void copyStream(Reader in, Writer out) throws IOException {
int b;
while ((b = in.read()) != -1) {
out.write(b);
}
}
I tried using debugger to find out the problem, and the debugger shows b = in.read() was assigned -1 at the first iteration of the while loop. Then I executed the code step by step while inspecting the file's content and found that "Hello" keyword got deleted from the file right after statementfinal FileWriter fos = new FileWriter(testFile); gets executed.
I first thought this was due to the InputStream and OutputStream were pointed to the same file so the file gets sort of "locked" by JVM for execution safety?
So I tried swapping those two lines:
FileWriter fos = new FileWriter(testFile);
FileReader fin = new FileReader(testFile);
And the result turned out the same: the file content got eliminated right after the statement FileWriter fos = new FileWriter(testFile);
My questions is: why the content gets cleaned out by FileWriter?. Is this some behavior related to FileDescriptor? Is there a way to read and write to the same file?
Just FYI,
copyStream() method is working fine, I have tested it with other tests.
It's not about using append() method instead of write()
The statement FileWriter fos = new FileWriter(testFile); truncates the existing file.
It does not make sense for you to use streaming access to read and write the same file, as this won't give reliable results. Use RandomAccessFile if you want to read / write the same file: this has calls to seek current position and perform read or writes at different positions of a file.
https://docs.oracle.com/javase/7/docs/api/java/io/RandomAccessFile.html
FileWriter actually deletes everything in a file before writing. To preserve the text, use
new FileWriter(file, true);
The true parameter is the append parameter of the filewriter. Otherwise it will just overwrite everything
code that should read html file and write the result another file the buffered writer writes the file but when the code is run with different urlit doesn't appends but rewrites the file and the previous content disappears
the solution recuired is that when jsoup iterates new html the result should add to output file and not rewrite
changed different writer types other than buffered writer
public class WriteFile
{
public static void main(String args[]) throws IOException
{
String url = "http://www.someurl.com/registers";
Document doc = Jsoup.connect(url).get();
Elements es = doc.getElementsByClass("a_code");
for (Element clas : es)
{
System.out.println(clas.text());
BufferedWriter writer = new BufferedWriter(new FileWriter("D://Author.html"));
writer.append(clas.text());
writer.close();
}
}
}
Don't mistake the append-method of the BufferedWriter as appending content to the file. It actually appends to the given writer.
To actually append additional content to the file you need to specify that when opening the file writer. FileWriter has an additional constructor parameter allowing to specify that:
new FileWriter("D://Author.html", /* append = */ true)
You may even be interested in the Java Files API instead, so you can spare instantating your own BufferedWriter, etc.:
Files.write(Paths.get("D://Author.html"), clas.text().getBytes(), StandardOpenOption.CREATE, StandardOpenOption.APPEND);
Your loop and what you are writing may further be simplifiable to something as follows (you may then even omit the APPEND-open option again, if that makes sense):
Files.write(Paths.get("D://Author.html"),
String.join("" /* or new line? */,
doc.getElementsByClass("a_code")
.eachText()
).getBytes(),
StandardOpenOption.CREATE, StandardOpenOption.APPEND);
What I want to achieve is to create a file regardless of whether the file exists or not.
I tried using File.createNewFile() but that will only create the file if it does not already exists. Should I use File.delete() and then File.createNewFile()?
Or is there a clearer way of doing it?
FileWriter has a constructor that takes 2 parameters too: The file name and a boolean. The boolean indicates whether to append or overwrite an existing file. Here are two Java FileWriter examples showing that:
Writer fileWriter = new FileWriter("c:\\data\\output.txt", true); //appends to file
Writer fileWriter = new FileWriter("c:\\data\\output.txt", false); //overwrites file
You can use a suitable Writer:
BufferedWriter br = new BufferedWriter(new FileWriter(new File("abc.txt")));
br.write("some text");
It will create a file abc.txt if it doesn't exist. If it does, it will overwrite the file.
You can also open the file in append mode by using another constructor of FileWriter:
BufferedWriter br = new BufferedWriter(new FileWriter(new File("abc.txt"), true));
br.write("some text");
The documentation for above constructor says:
Constructs a FileWriter object given a File object. If the second
argument is true, then bytes will be written to the end of the file
rather than the beginning.
Calling File#createNewFile is safe, assuming the path is valid and you have write permissions on it. If a file already exists with that name, it will just return false:
File f = new File("myfile.txt");
if (f.createNewFile()) {
// If there wasn't a file there beforehand, there is one now.
} else {
// If there was, no harm, no foul
}
// And now you can use it.
Am using StaX XMLEventReader and XMLEventWriter.
I need to make modified temporal copy of original xml file saved in byte array. If I do so (for debug, am writing to file):
public boolean isCrcCorrect(Path path) throws IOException, XPathExpressionException {
ByteArrayOutputStream output = new ByteArrayOutputStream();
XMLEventFactory eventFactory = XMLEventFactory.newInstance();
XMLEventReader reader = null;
XMLEventWriter writer = null;
StreamResult result;
String tagContent;
if (!fileData.currentFilePath.equals(path.toString())) {
parseFile(path);
}
try {
System.out.println(path.toString());
reader = XMLInputFactory.newInstance().createXMLEventReader(new FileReader(path.toString()));
//writer = XMLOutputFactory.newInstance().createXMLEventWriter(output);
writer = XMLOutputFactory.newInstance().createXMLEventWriter(new FileWriter("f:\\Projects\\iqpdct\\iqpdct-domain\\src\\main\\java\\de\\iq2dev\\domain\\util\\debug.xml"));
writer.add(reader);
writer.close();
} catch(XMLStreamException strEx) {
System.out.println(strEx.getMessage());
}
crc.reset();
crc.update(output.toByteArray());
System.out.println(crc.getValue());
//return fileData.file_crc == crc.getValue();
return false;
}
clone differs from origin
Source:
<VendorText textId="T_VendorText" />
Clone:
<VendorText textId="T_VendorText"></VendorText>
Why he is putting the end tag? There is no either in Source.
If you want a precise copy of a byte stream that happens to be an XML document, you must copy it as a byte stream. You can't copy it by providing a back-end to an XML parser because the purpose of the parser front-end to to isolate your code from features that can vary but which are semantically equivalent. Such as, in your case, the two means for indicating an empty element.
I created an xml using MarkupBuilder in groovy but how do i write it into a xml file in my project dir E:\tomcat 5.5\webapps\csm\include\xml
def writer = new StringWriter()
def xml = new MarkupBuilder(writer)
String[] splitted
xml.rows()
{ for(int i=0;i<lines.length-1;i++){
row()
{
for(int j=0;j<lines[i].length();j++)
{
splitted= lines[i].split(',');
}
name(splitted[0])
email(splitted[1])
}
}
}
here println writer.toString() prints my whole xml content but i need it in a file in my tomcat project's xml directory
Not to take away from the correct answers above, but you can make your code much more Groovy:
new File( "${System.properties['catalina.base']}/webapps/csm/include/xml/yourfile.xml" ).withWriter { writer ->
def xml = new MarkupBuilder( writer )
xml.rows {
lines.each { line ->
row {
def splitted = line.split( ',' )
name( splitted[0] )
email( splitted[1] )
}
}
}
}
Instead of using a StringWriter, use a FileWriter. Also use system property catalina.base to get the Tomcat homepath.
def writer = new FileWriter(new File(System.getProperty("catalina.base") + "/webapps/csm/include/xml/yourfile.xml"))
Note however that it's not the best place to save your runtime generated files. They will be deleted every time you redeploy your .war file.
How about:
new File('E:\tomcat 5.5\webapps\csm\include\xml\Foo.xml') << writer.toString()
Not sure if you need to double escape \\ file path on windoze...
Instead of using a StringWriter i used FileWriter
and as for the the path i did
def writer = new FileWriter("../webapps/csm/include/xml/data.xml" )
Finally this works :)
//class writer to write file
def writer = new StringWriter();
//builder xml
def xmlCreated = new MarkupBuilder(writer);
//file where will be write the xml
def fileXmlOut = new File("C:\\Users\\example\\Desktop\\example\\test.xml");
//method MarkupBuilder to xml
xmlCreated.mkp.xmlDeclaration(version: "1.0", encoding: "utf-8");
xmlCreated.playlist() {
list() {
//xml = your file xml parse
name xml.list.name.text()
}
eventlist () {
event(type: example.eventlist.#type)
}
}
//writing xml in file
fileXmlOut << writer.toString();