Invalid outout when writing to file with java - java

I'm trying to write the output to a csv file but the first values are in this format
I used ObjectOutputStream. Normally the first values should be 1,1,1,2,2,2,3....
Here is my code any ideas please ?
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.List;
import org.apache.mahout.cf.taste.common.TasteException;
import org.apache.mahout.cf.taste.impl.common.LongPrimitiveIterator;
import org.apache.mahout.cf.taste.impl.model.file.FileDataModel;
import org.apache.mahout.cf.taste.impl.recommender.GenericItemBasedRecommender;
import org.apache.mahout.cf.taste.impl.similarity.LogLikelihoodSimilarity;
import org.apache.mahout.cf.taste.model.DataModel;
import org.apache.mahout.cf.taste.recommender.RecommendedItem;
import org.apache.mahout.cf.taste.similarity.ItemSimilarity;
public class ItemRecommend {
public static void main(String[] args) throws IOException {
FileOutputStream fos = new FileOutputStream("data/test.csv");
ObjectOutputStream oos = new ObjectOutputStream(fos);
try {
DataModel dm = new FileDataModel(new File("data/rated.csv"));
ItemSimilarity sim = new LogLikelihoodSimilarity(dm);
GenericItemBasedRecommender recommender = new GenericItemBasedRecommender(dm, sim);
for (LongPrimitiveIterator items = dm.getItemIDs(); items.hasNext();){
long itemID = (int)(long) items.nextLong();
List<RecommendedItem>recommendations = recommender.mostSimilarItems(itemID, 3);
for(RecommendedItem recommendation : recommendations){
oos.writeObject(itemID + "," + recommendation.getItemID() + "," + recommendation.getValue()+"\n");
//System.out.println(itemID + "," + recommendation.getItemID() + "," + recommendation.getValue());
}
}
} catch (IOException e) {
System.out.println("Error !");
e.printStackTrace();
} catch (TasteException e) {
System.out.println("Taste exception !");
e.printStackTrace();
}
finally {
oos.flush();
oos.close();
}
}
}

You should try FileWriter or PrintWriter
http://www.journaldev.com/878/how-to-write-a-file-in-java-using-filewriter-bufferedwriter-files-and-fileoutputstream

Related

org.xml.sax.SAXParseException error while integrating XML for generating PDF

While Running the following code in order to read an XML file and generating a corresponding PDF. I am facing the errors mentioned below the code.
package com.test.pdf;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
import com.google.zxing.WriterException;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfDocument;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.pdf.parser.PdfTextExtractor;
import com.itextpdf.xmp.impl.Base64;
//import com.itextpdf.text.pdf.codec.Base64;
import org.apache.log4j.Logger;
public class PDFGenerator {
final static Logger logger = Logger.getLogger(PDFGenerator.class);
private static final String TITLE = "TestReport";
public static final String PDF_EXTENSION = ".pdf";
public static String arg1 = "";
public static String arg2 = "";
public static String arg3 = "";
public static String createPDFBase64(String arg1 , String arg2 , String arg3) throws IOException, URISyntaxException, com.lowagie.text.DocumentException, WriterException {
byte[] encoded = null;
String out= null;
Document document = new Document();
try {
//arg1 = args[0];
//Document is not auto-closable hence need to close it separately
document = new Document(PageSize.LETTER);
System.out.println("Here i amn777");
File temp = File.createTempFile(TITLE ,PDF_EXTENSION);
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(
temp)); // new File
HeaderFooter event = new HeaderFooter(arg2);
event.setHeader("Test Report");
writer.setPageEvent(event);
document.open();
PDFCreator pdfCreator = new PDFCreator();
pdfCreator.addMetaData(document, arg1 , arg2 );
pdfCreator.addTitlePage(document, arg2 );
//PDFCreator.addContent(document, dataObjList);
//String base64String = Base64.encodeFromFile("C:\\Users\\2000554\\Downloads\\HTMLToPDF\\TestReport.pdf");
//System.out.println("===============>>>" + base64String);
document.close();
byte[] inFileBytes = Files.readAllBytes(temp.toPath());
//PdfReader pReader = new PdfReader(inFileBytes);
//System.out.println("pReader.getFileLength()===============>>>" + pReader.getFileLength());
//System.out.println("pReader.getFileLength()===============>>>" + PdfTextExtractor.getTextFromPage(pReader, 1));
out = new String(Base64.encode(inFileBytes), "UTF-8");
System.out.println("Clear cache..");
pdfCreator.xmlData.clear();
pdfCreator.dataObjMRCList.clear();
pdfCreator.dataObjNRCList.clear();
pdfCreator.dataObjVASList.clear();
pdfCreator.dataObjDEVList.clear();
pdfCreator.stcPhoneNumDispList.clear();
pdfCreator.stcSvcMap.clear();
pdfCreator.stcSvcBandWthMap.clear();
pdfCreator.invoiceTaxDvcMap.clear();
//byte[] decoded = java.util.Base64.getDecoder().decode(out.getBytes());
/* byte[] decoded = Base64.decode(out.getBytes());
FileOutputStream fos = new FileOutputStream("C:\\Users\\2000554\\Downloads\\HTMLToPDF\\TestBaseReport.pdf");
fos.write(decoded);
fos.flush();
fos.close();*/
}catch ( FileNotFoundException e) {
System.out.println("FileNotFoundException occurs.." + e.getMessage());
e.printStackTrace();
}catch (DocumentException e) {
System.out.println("DocumentException occurs.." + e.getMessage());
e.printStackTrace();
} catch (Exception e) {
System.out.println("Exception occurs.." + e.getMessage());
e.printStackTrace();
return null;
}
finally{
if(null != document){
// document.close();
}
}
return out;
}
public static void main(String args[]) {
try {
if(args != null && args.length>1) {
FileReader fReader = new FileReader(new File("C:\\Users\\2004807\\Downloads\\XML\\Amendment.xml"));
BufferedReader bdr = new BufferedReader(fReader);
String line = null;
String xmlString = "";
while ((line=bdr.readLine())!=null){
xmlString += line;
}
createPDFBase64(xmlString,args[1],args[2]);
}else {
createPDFBase64("","","");
}
} catch (IOException e) {
e.printStackTrace();
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (com.lowagie.text.DocumentException e) {
e.printStackTrace();
} catch (WriterException e) {
e.printStackTrace();
}
}
}
I rechecked the path and the XML format since the error mentioned is due to wrong formatting of XML in some cases. I still am getting the following error.
Here i amn777
1getting resourcesfile:/C:/Users/2004807/Desktop/B2B%20Java/HtmlToPdf/target/classes/new.PNG
Inside getXMLData
XML==>
[Fatal Error] :1:1: Premature end of file.
Error is :org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 1; Premature end of file.
xmlData size is :0

Can i take a screenshot and paste it in a word file in appium using Java?

I'm currently using the below method to take screenshots and store them in a folder called 'Screenshots'. But what i want is, to take these screenshots and paste them in a word document according to the test cases to which they belong.
Is it possible? If so could somebody please guide me?
public String FailureScreenshotAndroid(String name) {
try {
Date d = new Date();
String date = d.toString().replace(":", "_").replace(" ", "_");
TakesScreenshot t = (TakesScreenshot)driver;
File f1 = t.getScreenshotAs(OutputType.FILE);//Temporary Location
String permanentLocation =System.getProperty("user.dir")+ "\\Screenshots\\"+name+date+".png";
File f2 = new File(permanentLocation);
FileUtils.copyFile(f1, f2);
return permanentLocation;
}catch (Exception e) {
String msg = e.getMessage();
return msg;
}
}
Try below:
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.concurrent.TimeUnit;
import javax.imageio.ImageIO;
import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFRun;
public class TakeScreenshots {
public static void main(String[] args) {
try {
XWPFDocument docx = new XWPFDocument();
XWPFRun run = docx.createParagraph().createRun();
FileOutputStream out = new FileOutputStream("d:/xyz/doc1.docx");
for (int counter = 1; counter <= 5; counter++) {
captureScreenShot(docx, run, out);
TimeUnit.SECONDS.sleep(1);
}
docx.write(out);
out.flush();
out.close();
docx.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void captureScreenShot(XWPFDocument docx, XWPFRun run, FileOutputStream out) throws Exception {
String screenshot_name = System.currentTimeMillis() + ".png";
BufferedImage image = new Robot()
.createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
File file = new File("d:/xyz/" + screenshot_name);
ImageIO.write(image, "png", file);
InputStream pic = new FileInputStream("d:/xyz/" + screenshot_name);
run.addBreak();
run.addPicture(pic, XWPFDocument.PICTURE_TYPE_PNG, screenshot_name, Units.toEMU(350), Units.toEMU(350));
pic.close();
file.delete();
}
}

Java to generate XML from excel

I have a spreadsheet based on which I have to generate a xml file. the file should respect a particular XSD structure and I have to do from Java.
The XML mapping is not working in excel because of "list of lists " issue.
what would be an ideal approach in java to create , domparser or jaxb ?
Any reference is helpful
Here is my code
package exceltoXML;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Writer;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.TreeMap;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.eclipse.jgit.*;
import org.eclipse.jgit.api.CommitCommand;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.PushCommand;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
public class readExcel_class1 {
public static Properties properties;
public static Enumeration<?> en;
public static String SourcePath;
public static String targetPath;
public static Map<String, String> propertiesCaseInsensitiveMap;
public static List<foldermap> foldermaps;
public static void main(String[] args) throws IOException, ParserConfigurationException, TransformerException {
// TODO Auto-generated method stub
Writer writer = null;
try {
foldermaps = new ArrayList<foldermap>();
properties=loadProperties(args[0]);
en=properties.propertyNames();
propertiesCaseInsensitiveMap=new TreeMap<String,String>(String.CASE_INSENSITIVE_ORDER);
while(en.hasMoreElements()){
String key=(String)en.nextElement();
propertiesCaseInsensitiveMap.put(key, properties.getProperty(key));
}
SourcePath=propertiesCaseInsensitiveMap.get("sourcepath");
targetPath=propertiesCaseInsensitiveMap.get("targetPath");
System.out.println("Source Path is "+ SourcePath + " and Target path is " + targetPath);
String fileName = "export_"+new Date().getTime() + ".json";
System.out.println("Output filename is " + fileName);
//System.out.println("Hi");
File myFile = new File("C:\\Users\\abcdra\\Desktop\\cicd\\git_push.xlsm");
FileInputStream fis = new FileInputStream(myFile);
String sourceFileName = SourcePath+fileName;
String targetFileName = targetPath+fileName;
System.out.println("Source FileName : " + sourceFileName);
System.out.println("Target FileName : " + targetFileName);
File file = new File(sourceFileName);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder1 = factory.newDocumentBuilder();
Document document = builder1.newDocument();
Element rootElement = document.createElement("importParams");
document.appendChild(rootElement);
rootElement.setAttribute("xmlns", "http://www.abc.io/oie/importControl/9" );
writer = new BufferedWriter(new FileWriter(file));
// Finds the workbook instance for XLSX file
XSSFWorkbook myWorkBook = new XSSFWorkbook (fis);
// Return first sheet from the XLSX workbook
XSSFSheet mySheet = myWorkBook.getSheetAt(1);
Iterator<Row> rowIterator = mySheet.iterator();
ArrayList<ArrayList<String>> data = new ArrayList<ArrayList<String>>();
foldermap foldermap = new foldermap();
while (rowIterator.hasNext()) {
//System.out.println("Current Row Number : " + rowIterator.next().getRowNum());
Row row = rowIterator.next();
if(row.getRowNum()==0 ){
continue; //just skip the rows if row number is 0
}
// For each row, iterate through each columns
Iterator<Cell> cellIterator = row.cellIterator();
ArrayList<String> rowData = new ArrayList<String>();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
switch (cell.getCellType()) {
case STRING:
//System.out.println ("String: " + cell.getRichStringCellValue ());
rowData.add(cell.getRichStringCellValue() + "");
//System.out.println("Inside cells");
if (cell.getColumnIndex() ==0 )
{
foldermap.setSourceProject(cell.getStringCellValue());
System.out.println("source project " + foldermap.getSourceProject());
}
if (cell.getColumnIndex() ==1 )
{
foldermap.setSourceFolderPath (cell.getStringCellValue());
}
if (cell.getColumnIndex() ==2 )
{
foldermap.setTargetProject(cell.getStringCellValue());
}
if (cell.getColumnIndex() ==3 )
{
foldermap.setTargetFolderPath( cell.getStringCellValue());
}
if (cell.getColumnIndex() ==4 )
{
foldermap.setRecursive(cell.getStringCellValue());
System.out.println("Recursive value " + foldermap.getRecursive());
}
if (cell.getColumnIndex() ==5 )
{
foldermap.setRecursive(cell.getStringCellValue());
System.out.println("Recursive value " + foldermap.getRecursive());
}
break;
case NUMERIC:
System.out.println ("String: " + cell.getNumericCellValue ());
break;
case BOOLEAN:
System.out.print(cell.getBooleanCellValue() + "\t");
break;
default :
}
}
// System.out.println("\n");
writer.write("\n ");
foldermaps.add(foldermap);
}
System.out.println("Writing to text file is completed...");
if (writer != null) {
writer.close();
}
TransformerFactory transformerFactory=TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(document);
//create target path if it does not exist
Element foldermaps1 = document.createElement("folderMaps");
rootElement.appendChild(foldermaps1);
System.out.println("Number of foldermap are " + foldermaps.size());
for (foldermap fm : foldermaps)
{
System.out.println("Source Project is " + fm.getSourceProject());
Element fmap = document.createElement("folderMap");
foldermaps1.appendChild(fmap);
fmap.setAttribute("sourceProject", fm.getSourceProject());
fmap.setAttribute("sourceFolderPath", fm.getSourceFolderPath());
fmap.setAttribute("targetProject", fm.getTargetProject());
fmap.setAttribute("targetFolderPath", fm.getTargetFolderPath());
fmap.setAttribute("recursive", fm.getRecursive());
}
StreamResult result = new StreamResult(new File("C:\\Users\\abcdra\\Desktop\\eclipse_workspace_64\\abc.xml"));
transformer.setOutputProperty
(OutputKeys.INDENT, "yes");
transformer.transform(source, result);
System.out.println("Parameter file successfully created");
}
catch(IOException ex )
{
ex.printStackTrace();
}
}
public static Properties loadProperties(String filename){
Properties props = new Properties();
InputStream input = null;
try {
input = new FileInputStream(filename);
props.load(input);
System.out.println("Loaded properties from: " + filename);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return props;
}
public static void fileCopy (File sourceDirectory , File targetDirectory)
{
try {
Files.copy(sourceDirectory.toPath(),targetDirectory.toPath());
}
catch(Exception e)
{
System.out.println("Error" + e);
}
}
}
The input is like
I am getting the output like
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<importParams xmlns="http://www.informatica.com/oie/importControl/9">
<folderMaps>
<folderMap recursive="truth" sourceFolderPath="Hive" sourceProject="Unknown1" targetFolderPath="import" targetProject="Unknown"/>
<folderMap recursive="truth" sourceFolderPath="Hive" sourceProject="Unknown1" targetFolderPath="import" targetProject="Unknown"/>
</folderMaps>
</importParams>
Both elements have value unknown1 , so the last element is repeating ,any idea how to avoid that. the output I am expecting is
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<importParams xmlns="http://www.informatica.com/oie/importControl/9">
<folderMaps>
<folderMap recursive="truth" sourceFolderPath="Hive" sourceProject="Unknown" targetFolderPath="import" targetProject="Unknown"/>
<folderMap recursive="truth" sourceFolderPath="Hive" sourceProject="Unknown1" targetFolderPath="import" targetProject="Unknown"/>
</folderMaps>
</importParams>
There is quite a bit of code here, but I think the issue is that the foldermap is not being created new each time inside the row loop.
foldermap foldermap = new foldermap();
while (rowIterator.hasNext()) {
...
foldermaps.add(foldermap);
}
So the foldermap is being updated, but added multiple times.
Move the new foldermap(); inside the while loop so that on each row, there is a new entry.
I think, if I read the code correctly, you can do:
while (rowIterator.hasNext()) {
foldermap foldermap = new foldermap();
...
As the foldermap does not need scope outside of the while loop for the rowIterator.

I'm trying to lock file exclusively on read

I'm trying to lock a file exclusively on read.
I am using Java 7 on Windows 7.
The files are copied to a directory, and then I want to to read them correctly after copy. That's why I'm trying lock file exclusively on read.
But my program read file in the middle.
Can anyone please help me with this? Thanks!
package test;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
public class FileLockMove {
public static void main(String[] args) {
FileSystem fs = FileSystems.getDefault();
File dir = new File("c:/test_source/");
while(true){
for (File file : dir.listFiles()) {
try (FileChannel fc = (new RandomAccessFile(file, "rw")).getChannel()){
FileLock lock = fc.tryLock();
if(lock != null){
System.out.println("lock is not null\t" + file.getName());
System.out.println("addBody: " + file.getAbsolutePath() + "\t" + file.length());
}else{
System.out.println("lock is null\t" + file.getName());
continue;
}
} catch (Exception e) {
System.out.println("fail:" + file.getName()+"\t" + e.getMessage());
}
try {
Files.move(file.toPath(), fs.getPath("c:/test_dest/",file.getName()));
} catch (IOException e) {
e.printStackTrace();
}
}
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Originally, the copy file is not Java, but I created a copy of my program slowly to confirm that I can lock exclusively.
package test;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
public class FileCopySlow{
public static void main(String[] args) {
String source = "C:/test_orig/";
String dst ="C:/test_source/";
File file = new File(source);
File[] files = file.listFiles(new FilenameFilter() {
#Override
public boolean accept(File dir, String name) {
if(name.matches(".*\\.bmp")){
return true;
}
return false;
}
});
for(File f: files){
copyStream(f, dst);
}
}
static void copyStream(File source,String dst){
try(BufferedInputStream br = new BufferedInputStream(new FileInputStream(source))){
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(dst+source.getName()));
byte[] buff = new byte[100];
int len = -1;
while((len = br.read(buff)) >-1){
out.write(buff,0,len);
out.flush();
Thread.sleep(100);
}
out.close();
System.out.println(source.getName() + "\tfinish");
}catch(Exception e){
e.printStackTrace();
}
}
}

using Java arraylist for storing data from scan from file

I am new to java, but not coding. I am trying to figure out java because it's part of my class this term and I am having a really hard problem grasping the idea of it and implementing things in java.
my problem Is that I am not sure if I am correctly using the arraylist to grab data from the scan of the file and input it into a arraylist to sort and print at a later time. I am just having issues picking up on java any help would be great since I am new to java.
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.regex.Pattern;
import java.util.ArrayList;
import java.util.*;
public class MissionCount
{
private static ArrayList<String> list = new ArrayList<String>();
// returns an InputStream that gets data from the named file
private static InputStream getFileInputStream(String fileName) throws Exception {
InputStream inputStream;
try {
inputStream = new FileInputStream(new File(fileName));
}
catch (FileNotFoundException e) { // no file with this name exists
inputStream = null;
throw new Exception("unable to open the file -- " + e.getMessage());
}
return inputStream;
}
public static void main(String[] args) {
if (args.length != 1) {
System.out.println("USage: MissionCount <datafile>");
//System.exit(1);
}
try {
System.out.printf("CS261 - MissionCount - Chad Dreher%n%n");
int crewcount = 0;
int misscount = 0;
InputStream log = getFileInputStream(args[0]);
Scanner sc = new Scanner(log);
sc.useDelimiter(Pattern.compile(",|\n"));
while (sc.hasNext()) {
String crewMember = sc.next();
list.add(crewMember);
String mission = sc.next();
list.add(mission);
}
sc.close();
// Add code to print the report here
}catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}
InputStream log = getFileInputStream(args[0]);
Change that line to as follows :-
File log = new File(args[0])
that should work!

Categories

Resources