Uploading/Downloading word file to/from Mysql - java

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.

Related

Why i cannot generate pdf file with itext

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();

JFileChooser.SetCurrentDirectory not working

I have a JFileChooser and I want to set the directory it opens using some information stored in a .txt file (I'm using a .txt file to persist the desired location between sessions). I can get the file, read the data and set it to a string, but when I try to use that string to set the directory I want to open it doesn't work. My code is roughly something like this:
//buffer contains a byte[] for "/Users/user/Documents/Work/folderToOpen"
desiredPath = new String(buffer);
jFileChooser1.setCurrentDirectory(new java.io.File(desiredPath));
After stepping through this, however, the current directory is set to /Users/user.
If anyone has any ideas about what I'm doing wrong or a better way to accomplish this I'd love to hear it.
Thank you
private static String LAST_FOLDER_USED = null;
//Get the desired file path for user preferences
String pluginRoot = System.getProperty("user.dir") + File.separator.toString();
//Create a file using the desired file Path
File userPreferences = new File(pluginRoot + File.separator + "UserPreferences.txt");
//Get a file called UserPreferences.txt from target/classes to create an input stream
String fileName = "UserPreferences.txt";
InputStream readInFile = getClass().getResourceAsStream(fileName);{
//Convert input stream to read from the desired file in the plug-in root ("filePath" Created Above)
try{
readInFile = new FileInputStream(userPreferences);
}
catch (IOException e){
e.printStackTrace();
}}
//Read the readInFile into a byte[]
String desiredPathToOpenImage;
byte[] buffer = new byte[1000];
int i = 0;{
try {
while((i = readInFile.read(buffer)) !=-1){
System.out.println(new String(buffer));
i++;
}}
catch (IOException e) {
e.printStackTrace();
};
//Convert byte[] to string (This should be the path to the desired folder when selecting an image)
desiredPathToOpenImage = new String(buffer);
}
//Create a New File using the desired path
File desiredPath = new File(desiredPathToOpenImage + File.separator + "prefs.txt");
public SelectImage(Viewer parent, boolean modal) {
super(parent, modal);
initComponents();
int returnVal = jFileChooser1.showOpenDialog(parent);
// Sets up arrays for storing file information to be passed back to the viewer class.
String[] filePath = new String[jFileChooser1.getSelectedFiles().length];
String[] fileName = new String[jFileChooser1.getSelectedFiles().length];
String[] fileDir = new String[jFileChooser1.getSelectedFiles().length];
if (returnVal == JFileChooser.APPROVE_OPTION) {
// Cycles through the selected files and stores each piece accordingly
for (int i = 0; i < jFileChooser1.getSelectedFiles().length; i++) {
File file = jFileChooser1.getSelectedFiles()[i];
filePath[i] = file.getPath();
fileName[i] = file.getName();
fileDir[i] = file.getParent();
}
}
parent.setFilePath(filePath, fileName, fileDir);
}
private void initComponents() {
jFileChooser1 = new javax.swing.JFileChooser();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
jFileChooser1.setMultiSelectionEnabled(true);
//Checks folder_Path to see if a value is present. If value is present sets jFileChooser Directory to that value
if(desiredPathToOpenImage.contains(File.separator)){
//Create a File using the desired path for selecting images
//****Currently doesn't set the Directory correctly****//
jFileChooser1.setCurrentDirectory(desiredPath);
}
//If no value is present in LAST_FOLDER_USED sets jFileChooser Directory to desktop
else{
jFileChooser1.setCurrentDirectory(new java.io.File("/Users/benwoodruff/Desktop"));
}
jFileChooser1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jFileChooser1ActionPerformed(evt);
//After file is selected sets value of LAST_FOLDER_USED to the absolute path of that file
LAST_FOLDER_USED = jFileChooser1.getCurrentDirectory().toString() + File.separator + "UserPreferences.txt";
try {
FileWriter fileWriter = new FileWriter(userPreferences);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write(jFileChooser1.getCurrentDirectory().toString());
OutputStream outPut = new FileOutputStream(pluginRoot + File.separator + "UserPreferences.txt");
outPut.write(LAST_FOLDER_USED.getBytes());
outPut.close();
bufferedWriter.close();
} catch (IOException e) {
System.out.println("Error Writing to File" + desiredPathToOpenImage);
e.printStackTrace();
}
}
});
I think the directory passed as argument does not exist or is not accessible to the user you are logged in with judging from the javadoc of setCurrentDirectory():
If the file passed in as currentDirectory is not a directory, the parent of the file will be used as the currentDirectory. If the parent is not traversable, then it will walk up the parent tree until it finds a traversable directory, or hits the root of the file system.
Make sure all folders in the given path exist and are accessible to the logged user (on linux the 'executable' bit controls the accessibility of a directory). So if you see something like
-d x Documents
after executing
ls -l *
in a shell then the Documents directory is accessible.
Found a better way to accomplish my goal using Preferences instead of trying to create and access files to store the location.
Preferences prefs = Preferences.userNodeForPackage(this.getClass());
static String LAST_FOLDER_USED = "LAST_FOLDER_USED";
String folder_Location;
and then inside initComponents()
if(LAST_FOLDER_USED != null){
jFileChooser1.setCurrentDirectory(new File(prefs.get(LAST_FOLDER_USED, LAST_FOLDER_USED)));
}
else{
jFileChooser1.setCurrentDirectory(new java.io.File("/Users/benwoodruff/Desktop"));
}
jFileChooser1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jFileChooser1ActionPerformed(evt);
folder_Location = jFileChooser1.getCurrentDirectory().toString();
prefs.put(LAST_FOLDER_USED, folder_Location);
//System.out.println(prefs.get(LAST_FOLDER_USED, folder_Location));
}
});

JFileChooser / FileWriter doesn't let me save in root of C: disk

I'm playing around and I made a notepad-like app using swing. Everything is working properly so far, except it's not letting me save the text file directly on C:/. On any other disk, and INCLUDING the root of the D: drive, or in folders of the C:/ disk it works like a charm. Why is this happening?
This is my code:
file_save.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JFileChooser Chooser = new JFileChooser();
File DefaultDirectory = new File("C:/");
File Path;
int Checker;
FileFilter text_filter = new FileNameExtensionFilter(
"Text File (*txt)", "txt");
FileFilter another_filter = new FileNameExtensionFilter(
"Debug Filter (*boyan)", "boyan");
//
Chooser.setCurrentDirectory(DefaultDirectory);
Chooser.setDialogTitle("Save a file");
Chooser.addChoosableFileFilter(text_filter);
Chooser.addChoosableFileFilter(another_filter);
Chooser.setFileFilter(text_filter);
Checker = Chooser.showSaveDialog(null);
//
if (Checker == JFileChooser.APPROVE_OPTION) {
Path = Chooser.getSelectedFile();
System.out.println(Path.getAbsolutePath());
;// Just for
// debugging.
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter(Path
.getAbsolutePath()));
String[] myString = textArea.getText().split("\\n");
for (int i = 0; i < textArea.getLineCount(); i++) {
writer.append(myString[i]);
writer.newLine(); // SO IT CAN PRESERVE NEW LINES
// (APPEND AND SPLIT ARE ALSO
// THERE
// BECAUSE OF THAT)
writer.flush();
}
JOptionPane.showMessageDialog(null, "File saved.", "",
JOptionPane.WARNING_MESSAGE);
} catch (IOException e) {
JOptionPane.showMessageDialog(null,
"File did not save successfuly.", "",
JOptionPane.WARNING_MESSAGE);
} finally {
try {
if (writer != null)
writer.close();
} catch (IOException e) {
JOptionPane.showMessageDialog(null,
"File did not save successfuly.", "",
JOptionPane.WARNING_MESSAGE);
}
}
}
}
});
Thanks a lot in advance!
Usually, one does not have write permissions in C:\.
Start the app as a privileged user
One should not do that, as it is not intended by OS design. Changing permissions on C:\, or the system drive respectively, is a no-go.
Save into a sub-directory of System.getProperty("user.home"); (way to go)
The user home could also be a network folder with nighly backup in a domain network, for example. Especially for remote sessions (RDP, Citrix), this is often the case.
If you absolutely need to install a static file outside of the users folders, do it once, with an installer, configured to raise privileges (UAC).

There is no existence of the saved file.How to do that?

while i am trying to save the file its not working but for making folders it works. what should i do ? i am new in java also. plz help
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==save)
{
JFrame parentFrame = new JFrame();
JFileChooser fileChooser = new JFileChooser();
fileChooser.setDialogTitle("Specify a file to save");
int userSelection = fileChooser.showSaveDialog(parentFrame);
if (userSelection == JFileChooser.APPROVE_OPTION)
{
File fileToSave = fileChooser.getSelectedFile();
System.out.println("Save as file: " + fileToSave.getAbsolutePath());
}
}
}
You choose a file but don't create it write anything to it. The file will not be created until you actually create it or write something to it, for example with
FileWriter writer = new FileWriter(fileToSave);
writer.write("Hello!");
writer.close();
First, get the file you want to save as a File.
Then, write it to a new directory using BufferedWriter to a new directory.
final JFileChooser fc = new JFileChooser();
int returnVal = fc.showSaveDialog(aComponent); //parent component to JFileChooser
if (returnVal == JFileChooser.APPROVE_OPTION) { //OK button pressed by user
File file = fc.getSelectedFile(); //get File selected by user
o = new BufferedWriter(new FileWriter(file)); //use its name
//write things here
o.flush();
o.close();
}
Look at How to save file using JFileChooser in Java? and How to save a txt file using JFileChooser?

Screenshot of gui, choose where to save question

I have a program that takes a screenshot of my gui. It automatically saves the .gif file to the eclipse project directory. What I would like is to have it asking a user where to save the image. Basically so the user can browse the file directory and choose the directory.
Here's the code I have:
public void actionPerformed(ActionEvent event) {
try{
String fileName = JOptionPane.showInputDialog(null, "Save file",
null, 1);
if (!fileName.toLowerCase().endsWith(".gif")){
JOptionPane.showMessageDialog(null, "Error: file name must end with \".gif\".",
null, 1);
}
else{
BufferedImage image = new BufferedImage(panel2.getSize().width,
panel2.getSize().height, BufferedImage.TYPE_INT_RGB);
panel2.paint(image.createGraphics());
ImageIO.write(image, "gif", new File(fileName));
JOptionPane.showMessageDialog(null, "Screen captured successfully.",
null, 1);
}
}
catch(Exception e){}
I would use a file chooser dialog instead of a JOptionPane. Here is a link for the tutorial.
Example:
First of all you have to declare JFileChooser object in your class and initialize it.
public Class FileChooserExample{
JFileChooser fc;
FileChooserExample(...){
fc = new JFileChooser();// as a parameter you can put path to initial directory to open
...
}
Now create another method:
private String getWhereToSave(){
int retVal = fc.showSaveDialog(..);
if(retVal == JFileChooser.APPROVE_OPTION){
File file = fc.getSelectedFile();
return file.getAbsolutePath();
}
return null;
}
This method returns to you the absolute path which user selected. retVal indicates which button was pressed (Save or Cancel). And if it was pressed Save then you handle the selected file.
Then you have this method you can incorporate this with your code. Instead of this line:
String fileName = JOptionPane.showInputDialog(null, "Save file", null, 1);
Write:
String fileName = getWhereToSave();

Categories