I'm trying to add data to Word document in my automation using JavatoWord API and Word is getting corrupted when I append the data. Can anyone help?
import java.io.*;
import java.text.*;
import java.util.*;
import word.api.interfaces.IDocument;
import word.w2004.Document2004;
import word.w2004.Document2004.Encoding;
import word.w2004.elements.BreakLine;
import word.w2004.elements.Image;
import word.w2004.elements.ImageLocation;
import word.w2004.elements.Paragraph;
import word.w2004.elements.ParagraphPiece;
public void AppendtoWord() throws Exception
{
String strScrShotsFile = "C:/Test.doc/";
String ScrShotsFile = "C:/test.png";
File fileScrShotsFile = new File (strScrShotsFile);
boolean exists = (fileScrShotsFile).exists();
PrintWriter writer = null;
myDoc = new Document2004();
if (!exists) {
try {
writer = new PrintWriter(fileScrShotsFile);
myDoc.encoding(Encoding.UTF_8);
myDoc.company("Comp Inc");
myDoc.author("Test Automation Teams");
myDoc.title("Application Automation Test Results");
myDoc.subject("Screen Shots");
myDoc.setPageOrientationLandscape();
myDoc.addEle(BreakLine.times(2).create());// Document Header and Footer
myDoc.addEle(BreakLine.times(2).create());
myDoc.getHeader().addEle(
Paragraph.withPieces(
ParagraphPiece.with("Screenshots for test case: "),
ParagraphPiece.with( "Test" ).withStyle().bold().create()
).create()
);
myDoc.getFooter().addEle(Paragraph.with(ScrShotsFile).create()); // Images
myDoc.addEle(BreakLine.times(1).create());
myDoc.addEle(Paragraph.with("Test").withStyle().bgColor("RED").create());
writer.println(myDoc.getContent());
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
writer.close();
}
} else {
PrintWriter writer1= null;
try {
writer1 = new PrintWriter(new FileWriter(fileScrShotsFile,true));
myDoc.addEle(Paragraph.with("This is Important").withStyle().bgColor("RED").create());
writer1.println(myDoc.getContent());
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
writer1.close();
}
}
Related
I have a file called "ParkPhotos.txt" and inside I have 12 names of some parks, for example "AmericanSamoa1989_photo.jpg". I want to replace the "_photo.jpg" to "_info.txt", but I am struggling. In the code I was able to read the file, but I am not sure how to replace it.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class FileNameChange {
public static void main(String[] args) throws IOException
{
readFileValues();
}
public static void readFileValues() throws IOException
{
try {
File aFile = new File("ParkPhotos.txt");
Scanner inFile = new Scanner(aFile);
while (inFile.hasNextLine())
{
String parkNames = inFile.nextLine();
System.out.println(parkNames);
}
inFile.close();
} catch (FileNotFoundException e)
{
System.out.println("An error has occurred");
e.printStackTrace();
}
}
}
You can convert to a new content and write it to the current file. For example:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Scanner;
public class FileNameChange {
public static void main(String[] args) throws URISyntaxException {
String newContent = readFileValues();
writeFileValues(newContent);
}
public static String readFileValues() {
StringBuilder newContent = new StringBuilder();
try {
URL url = FileNameChange.class.getClassLoader().getResource("ParkPhotos.txt");
File aFile = new File(url.toURI());
Scanner inFile = new Scanner(aFile);
while (inFile.hasNextLine()) {
String parkName = inFile.nextLine();
if (parkName == null || parkName.isEmpty()) {
continue;
}
newContent.append(parkName.replace("_photo.jpg", "_info.txt"))
.append(System.lineSeparator());
}
inFile.close();
} catch (FileNotFoundException | URISyntaxException e) {
e.printStackTrace();
}
return newContent.toString();
}
public static void writeFileValues(String content) throws URISyntaxException {
URL url = FileNameChange.class.getClassLoader().getResource("ParkPhotos.txt");
File aFile = new File(url.toURI());
try (FileWriter writer = new FileWriter(aFile)) {
writer.write(content);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Note: the file will be written at build folder. For example: example_1/build/resources/main
For example we have a .txt file:
Name smth
Year 2012
Copies 1
And I want to replace it with that:
Name smth
Year 2012
Copies 0
Using java.io.*.
Here is the code that does that. Let me know if you have any question.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.LinkedHashMap;
import java.util.Map;
public class Test2 {
Map<String, String> someDataStructure = new LinkedHashMap<String, String>();
File fileDir = new File("c:\\temp\\test.txt");
public static void main(String[] args) {
Test2 test = new Test2();
try {
test.readFileIntoADataStructure();
test.writeFileFromADataStructure();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
private void readFileIntoADataStructure() throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(
new FileInputStream(fileDir)));
String line;
while ((line = in.readLine()) != null) {
if (line != null && !line.trim().isEmpty()) {
String[] keyValue = line.split(" ");
// Do you own index and null checks here this is just a sample
someDataStructure.put(keyValue[0], keyValue[1]);
}
}
in.close();
}
private void writeFileFromADataStructure() throws IOException {
Writer out = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(fileDir)));
for (String key : someDataStructure.keySet()) {
// Apply whatever business logic you want to apply here
myBusinessMethod(key);
out.write(key + " " + someDataStructure.get(key) + "\n");
out.append("\r\n");
out.append("\r\n");
}
out.flush();
out.close();
}
private String myBusinessMethod(String data) {
if (data.equalsIgnoreCase("Copies")) {
someDataStructure.put(data, "0");
}
return data;
}
}
Read your original text file line by line and separate them into string tokens delimited by spaces for output, then when the part you want replaced is found (as a string), replace the output to what you want it to be. Adding the false flag to the filewrite object ("filename.txt", false) will overwrite and not append to the file allowing you to replace the contents of the file.
this is the code to do that
try {
String sCurrentLine;
BufferedReader br = new BufferedReader(new FileReader("yourFolder/theinputfile.txt"));
BufferedWriter bw = new BufferedWriter(new FileWriter("yourFolder/theinputfile.txt" , false));
while ((sCurrentLine = br.readLine()) != null) {
if(sCurrentLine.indexOf("Copies")>=0){
bw.write("Copies 0")
}
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close()bw.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
hopefully that help
I am new to XML.After a lot of search i found XMLUnit to do that but the problem am getting is :
whenever i change the contents of xml file to simple string text and try to execute the code ,it still shows green in junit test which it should not do although it is throwing an exception but my requirement is the signal should be red even the files are not in proper xml format.Enclosing my work for so far.
package mypack;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;
import org.custommonkey.xmlunit.DetailedDiff;
import org.custommonkey.xmlunit.Diff;
import org.custommonkey.xmlunit.XMLTestCase;
import org.custommonkey.xmlunit.XMLUnit;
import org.junit.Test;
import org.xml.sax.SAXException;
public class MyXMLTestCase extends XMLTestCase {
enter code here
#Test
public void testMyXmlTestCase() {
FileReader expected = null;
FileReader output = null;
try {
expected = new FileReader("D:/vivek.xml");
output = new FileReader("D:/rahul.xml");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
XMLUnit.setNormalizeWhitespace(Boolean.TRUE);
try {
Diff diff = new Diff(expected,output);
// assertTrue("XMLSimilar"+diff.toString(),diff.similar());
//assertTrue("XMLIdentical"+diff.toString(),diff.identical());
DetailedDiff mydiff = new DetailedDiff(diff);
List allDifferences = mydiff.getAllDifferences();
assertEquals(mydiff.toString(), 0, allDifferences.size());
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I wrote a very simple piece of code, It was working perfectly since yesterday but now not working and even after lots of research/debugging i have not got the issue
import java.net.InetAddress;
import java.util.Date;
import java.io.File;
import java.io.FileWriter;
import java.io.BufferedWriter;
public class DetectLoggedInUser{
public static void returnUserName()
{
String computerName;
try {
File file =new File("d:\\TestFolder\\UsersloggedIn.txt");
if(!file.exists()){
file.createNewFile();
}
FileWriter fileWritter = new FileWriter(file.getName(),true);
BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
String content= "\n UserName="+System.getProperty("user.name")+ " || Date and Time= "+new Date();
bufferWritter.write(content);
bufferWritter.close();
}
catch(Exception ex) {
ex.printStackTrace();
}
}
public static void main(String args[])
{
returnUserName();
}
}
Now file is created but nothing is being written in file
Is there anything wrong with this code(keeping in mind it was working since yesterday)?
Try this:
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.Date;
public class DetectLoggedInUser {
public static void returnUserName() {
try {
File file = new File("d:\\TestFolder\\UsersloggedIn.txt");
if (!file.exists()) {
file.createNewFile();
}
FileWriter fileWritter = new FileWriter(file, true);
BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
String content = "\n UserName=" + System.getProperty("user.name")
+ " || Date and Time= " + new Date();
bufferWritter.write(content);
bufferWritter.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static void main(String args[]) {
returnUserName();
}
}
You can use
FileWriter fileWritter = new FileWriter(file.getAbsolutePath(), true);
Instead of file.getName() in your code.File.getName() method returns only the name of the file or directory,not the absolute path;
You don't need to check if the files exists or not, beside that it works fine for me.
I looked into at4j and 7-Zip-JBinding (their javadoc and documentation) but they doesn't seem to be able to read without extracting (and get an InputStream from archived file)
Is there any method I'm missing or haven't found ?
a solution other than extracting to a temporary folder to read it
I'm expecting an answer in how to do it in at4j or 7-Zip-JBinding
in other words I want to know how to utilize below mentioned function in at4j or 7-Zip-JBinding
I know java's built in one has getInputStream I'm currently using it this way
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
/**
* get input stream of current file
* #param path path inside zip
* #return InputStream
*/
public InputStream getInputStream(String path){
try {
ZipEntry entry = zipFile.getEntry(path);
if(entry!=null){
return zipFile.getInputStream(entry);
}
return new ByteArrayInputStream("Not Found".getBytes());
} catch (Exception ex) {
//handle exception
}
return null;
}
(^^ zipFile is a ZipFile object)
found the solution using 7-Zip-JBinding
just need to use ByteArrayInputStream ,this so far worked for a small file
pass a archive as argument to get all files inside printed
file ExtractItemsSimple.java
import java.io.IOException;
import java.io.RandomAccessFile;
import net.sf.sevenzipjbinding.ISevenZipInArchive;
import net.sf.sevenzipjbinding.SevenZip;
import net.sf.sevenzipjbinding.SevenZipException;
import net.sf.sevenzipjbinding.impl.RandomAccessFileInStream;
import net.sf.sevenzipjbinding.simple.ISimpleInArchive;
import net.sf.sevenzipjbinding.simple.ISimpleInArchiveItem;
public class ExtractItemsSimple {
public static void main(String[] args) {
RandomAccessFile randomAccessFile = null;
ISevenZipInArchive inArchive = null;
try {
randomAccessFile = new RandomAccessFile(args[0], "r");
inArchive = SevenZip.openInArchive(null, // autodetect archive type
new RandomAccessFileInStream(randomAccessFile));
ISimpleInArchive simpleInArchive = inArchive.getSimpleInterface();
for (ISimpleInArchiveItem item : simpleInArchive.getArchiveItems()) {
final int[] hash = new int[] { 0 };
if (!item.isFolder()) {
System.out.println(ArchieveInputStreamHandler.slurp(new ArchieveInputStreamHandler(item).getInputStream(),1000));
}
}
} catch (Exception e) {
System.err.println("Error occurs: " + e);
System.exit(1);
} finally {
if (inArchive != null) {
try {
inArchive.close();
} catch (SevenZipException e) {
System.err.println("Error closing archive: " + e);
}
}
if (randomAccessFile != null) {
try {
randomAccessFile.close();
} catch (IOException e) {
System.err.println("Error closing file: " + e);
}
}
}
}
}
file ArchieveInputStreamHandler.java
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import net.sf.sevenzipjbinding.ISequentialOutStream;
import net.sf.sevenzipjbinding.SevenZipException;
import net.sf.sevenzipjbinding.simple.ISimpleInArchiveItem;
public class ArchieveInputStreamHandler {
private ISimpleInArchiveItem item;
private ByteArrayInputStream arrayInputStream;
public ArchieveInputStreamHandler(ISimpleInArchiveItem item) {
this.item = item;
}
public InputStream getInputStream() throws SevenZipException{
item.extractSlow(new ISequentialOutStream() {
#Override
public int write(byte[] data) throws SevenZipException {
arrayInputStream = new ByteArrayInputStream(data);
return data.length; // Return amount of consumed data
}
});
return arrayInputStream;
}
//got from http://stackoverflow.com/questions/309424/read-convert-an-inputstream-to-a-string
public static String slurp(final InputStream is, final int bufferSize){
final char[] buffer = new char[bufferSize];
final StringBuilder out = new StringBuilder();
try {
final Reader in = new InputStreamReader(is, "UTF-8");
try {
for (;;) {
int rsz = in.read(buffer, 0, buffer.length);
if (rsz < 0)
break;
out.append(buffer, 0, rsz);
}
}
finally {
in.close();
}
}
catch (UnsupportedEncodingException ex) {
/* ... */
}
catch (IOException ex) {
/* ... */
}
return out.toString();
}
}
Are you looking for http://docs.oracle.com/javase/6/docs/api/java/util/zip/ZipInputStream.html which can extract entries in zip file without extracting it completely.