So I tried to get data from my [database] table then generate a PDF from it. First, I tried to select the directory where I want to save the file with JFileChooser. Then, I tried to create the PDF inside the selected directories. Last, I tried to get all the data from my DB and insert it to my PDF.
The problem is that the PDF file is not generated and there is no error message showing.
String path = "";
JFileChooser j = new JFileChooser();
j.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int x = j.showSaveDialog(this);
if(x == JFileChooser.APPROVE_OPTION){
path = j.getSelectedFile().getPath();
}
try{
Document doc = new Document();
PdfWriter.getInstance(doc, new FileOutputStream(path + "abcd123.pdf"));
doc.open();
PdfPTable tbl = new PdfPTable(2);
tbl.addCell("Class ID");
tbl.addCell("Class Name");
try{
String query = "SELECT * FROM kelas";
PreparedStatement st = (PreparedStatement)conn.prepareStatement(query);
ResultSet rs = st.executeQuery();
while(rs.next()) {
tbl.addCell(rs.getString("id"));
tbl.addCell(rs.getString("nama"));
}
} catch (SQLException ex) {
ex.printStackTrace();
}
doc.add(tbl);
doc.close();
} catch (Exception e) {
System.err.println(e);
}
So I tried to change the path from
PdfWriter.getInstance(doc, new FileOutputStream(path + "abcd123.pdf"))
to
PdfWriter.getInstance(doc, new FileOutputStream("C:\\Users\\Daniel\\Desktop\\tes.pdf"));
And it works. But I want the path to be dynamic and not hard coded.
So from your last edit of your question I will suggest to try
PdfWriter.getInstance(doc, new FileOutputStream(path + "\\abcd123.pdf"));
Also you can try to print the path to see what is the value of it.
By the way you should use file separator that works on Windows and Unix(Linux):
String fileSeparator = FileSystems.getDefault().getSeparator();
Related
I'm reading a file, adding some data to paragraphs, and then writing out a document another file.
The problem I'm facing is that the output file is unreadable, I can't open it, and if a binary open it I can see that it don't have the correct format.
Every character has a ? character at the left side.
Can you give me some advice about what is happening?
Wrong output
Correct output
EDIT: Code Save function
FileOutputStream out = null;
try {
// Add true to make the data append possible in output stream.
out = new FileOutputStream(filePath, true);
doc.write(out);
out.flush();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
out.close();
}
Edit file:
File file = new File("muestra.doc");
FileInputStream fis = new FileInputStream(file.getAbsolutePath());
POIFSFileSystem fs = new POIFSFileSystem(fis);
HWPFDocument document = new HWPFDocument(fs);
Range range = document.getRange();
for (int i = 0; i < document.getParagraphTable().getParagraphs().size(); i++) {
Paragraph p = range.getParagraph(i);
p.insertBefore("£");
}
How are you?
Within a project that I am doing I need to obtain an image of the computer and save it in a database, for this I used the field input type = file.
To save it I use the following function:
public boolean guardarfoto(int idProducto, String imagen) {
FileInputStream fis = null;
try {
File file = new File("C:\\" + imagen);
fis = new FileInputStream(file);
cpsql.conectar();
connection = ConexionPgSQL.getCn();
PreparedStatement pstm = connection.prepareStatement("UPDATE productos SET imagen_producto = ?, nombre_imagen = ? where id_producto = ?");
pstm.setBinaryStream(1, fis, (int) file.length());
pstm.setString(2, imagen);
pstm.setInt(3, idProducto);
pstm.execute();
System.out.println("Agregando imagen: " + pstm.toString());
pstm.close();
return true;
} catch (FileNotFoundException | SQLException e) {
Logger.getLogger(ControladorProducto.class.getName()).
log(Level.SEVERE, null, e);
}
return false;
}
My problem is that this function only allows me to save an image that is inside the specified directory, in this case C: \, because if in the function I replaced the File file = new File ("C: \\" + image); by File file = new File (image); it seems to try to look for the route internally in the project, and not in the directory of the computer, and would therefore like to replace that static directory with a dynamic one so as not to limit the client to having to move the image to the specified route so that Do not mark error when saving.
For this, I am working on a Web project using NetBeans 8.0.2, JSPs and Servlets.
I am writing to an existing excel file using Java, say this is fileA. (I'm using APACHE POI for this.)
It is possible that the excel fileA is opened by someone. It is saved in a shared folder accessed by a lot of people.
I want to avoid encountering
java.io.FileNotFoundException: (The process cannot access the file
because it is being used by another process)
Because no matter if the existing excel file is opened or not, I need to save the output of my Java app.
Upon researching, I think it is impossible to close fileA (opened by some other process/user, not by my Java App) within my Java code.
What I'm doing now is to create a new excel file, say fileB if fileA is currently opened. I'm using the code below.
File file = null;
FileOutputStream out = null;
int workbookNo = 0;
do{
String append = "";
if(workbookNo != 0){
append = "_Copy" + Integer.toString(workbookNo);
}
file = new File(filePath + "ValidateLock_" + dataDate + append + ".xlsx");
try{
out = new FileOutputStream(file);
workbookNo = 0;
}catch(FileNotFoundException e){
//e.printStackTrace();
workbookNo++;
}
}while(workbookNo != 0);
However, I'm getting the error below.
org.apache.poi.openxml4j.exceptions.NotOfficeXmlFileException: No
valid entries or contents found, this is not a valid OOXML (Office
Open XML) file
try like this :
try {
FileInputStream file = new FileInputStream(new File("C:\\update.xls"));
HSSFWorkbook workbook = new HSSFWorkbook(file);
HSSFSheet sheet = workbook.getSheetAt(0);
Cell cell = null;
//Update the value of cell
cell = sheet.getRow(1).getCell(2);
cell.setCellValue(cell.getNumericCellValue() * 2);
cell = sheet.getRow(2).getCell(2);
cell.setCellValue(cell.getNumericCellValue() * 2);
cell = sheet.getRow(3).getCell(2);
cell.setCellValue(cell.getNumericCellValue() * 2);
//Close the excel input file (inputstream)
file.close();
FileOutputStream outFile =new FileOutputStream(new File("C:\\update.xls"));
workbook.write(outFile);
//Close output excel file
outFile.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
I am in the process of creating an app that allows a user to fill in a from and upload their CV to a potential employer. At the moment I am stuck on uploading the CV to my database.
//File chooser
JFileChooser fc = new JFileChooser();
fc.setCurrentDirectory(new java.io.File("C:\\Users\\Dawid\\Desktop"));
fc.setDialogTitle("CV Upload");
fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
/*********************************************/
//Buttons
JButton open = new JButton();
JButton btnBrowse = new JButton("Browse");
btnBrowse.setBounds(312, 172, 89, 23);
qualifications.add(btnBrowse);
btnBrowse.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0)
{
if(fc.showOpenDialog(open) == JFileChooser.APPROVE_OPTION);
CvUploadTextField.setText(fc.getSelectedFile().getAbsolutePath());
}
});
This piece of Code sets up my File chooser and prints out the filepath on a text box. What i would hope to achieve is to be able to take the filepath from that textbox and be able to upload that file to the database, in a similar fashion to the below.
try
{
Class.forName(driver).newInstance();
Connection conn = DriverManager.getConnection(url+dbName,userName,password);
Statement st = conn.createStatement();
ResultSet res = st.executeQuery("SELECT * FROM javaapp.test");
int val = st.executeUpdate("INSERT INTO javaapp.test (Name,DOB,Phone,Email,Q1Name,Q1Title,Q2Name,Q2Title,W1Name,W1From,W1To,W2Name,W2From,W2To,About)"
+ " VALUES ('"+Name+"','"+DOB+"','"+Phone+"','"+Email+"','"+Q1Name+"','"+Q1Title+"','"+Q2Name+"','"+Q2Title+"','"+W1Name+"','"+W1From+"',"
+ "'"+W1To+"','"+W2Name+"','"+W2From+"','"+W2To+"','"+About+"')");
if(val==1)
System.out.print("Successfully inserted value");
conn.close();
}
catch (Exception e)
{
e.printStackTrace();
}
I know files aren't like strings and integers so I cannot figure out how to do it. Any help would be appreciated.
Thank You
JFileChooser has a method, getSelectedFile(). Which is a File. You can
If you want to allow only .doc, .docx extensions set
JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter(
"word docs only", "doc", "docx");
chooser.setFileFilter(filter);
The save it as
File selectedFile = chooser.getSelectedFile();
try {
String fileName = selectedFile.getCanonicalPath();
if (!fileName.endsWith(EXTENSION)) {
selectedFile = new File(fileName + EXTENSION);
}
ImageIO.write(image, FORMAT_NAME, selectedFile);
} catch (IOException e) {
e.printStackTrace();
If you want to upload word files to a database you might want to look up BLOB datatype for mysql and also byte arrays for java.
RECOMMENDATION:
It would be ideal to store files on your SERVER and store the directory path for those files in your database so you know where to look when retrieving them. This would not only be an easy implementation but also wise.
I want to make a path that saved in database.
here's my code.
#RequestMapping("import_excel")
#ResponseBody
public Map<String, ? extends Object> import_excel() {
modelMap.clear();
try {
HttpSession session = req.getSession();
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("Export");
Row row1 = sheet.createRow((short) 3);
row1.createCell(0).setCellValue("Asset Number");
row1.createCell(1).setCellValue("Asset Barcode");
row1.createCell(2).setCellValue("Asset Name");
short i = 4;
Row row2 = sheet.createRow(i++);
row2.createCell(0).setCellValue(as.getCdas());
row2.createCell(1).setCellValue(as.getBcd());
row2.createCell(2).setCellValue(as.getNm());
FileOutputStream fileOut = new FileOutputStream(src + "/Export.xls");
wb.write(fileOut);
fileOut.close();
modelMap.put("success", true);
modelMap.put("rows", obj);
modelMap.put("count", count);
} catch (IOException ex) {
modelMap.put("success", false);
modelMap.put("msg", ex.getMessage());
}
return modelMap;
}
I want to make FileOutputStream fileOut = new FileOutputStream(src + "/Export.xls"); with the path I save in db. so If I want to change the path I just change in db.
I've tried code above but doesnt seems work.
please help me. Thanks :)
I would suggest that use it programmatically...
use
String PathTillProject = System.getProperty("user.dir");
This will give you the system path one level up to src i.e. till your project (I assume your src is just within your project directory). For example if your project name is TestProject then location or src is TestProject/src. Now you can use it like:
String PathTillProject = System.getProperty("user.dir");
FileOutputStream fileOut = new FileOutputStream(PathTillProject + "/src/Export.xls");