Java Uploading Image Path To Mysql Missing '/' - java

I want to upload a path of an image to mysql database but whenever i tried to upload it, it always upload the path without '/'. example i have a file in src/upload/nameofimage.jpg, in the database it's srcuploadnameofimage.jpg
here is the upload button that i have
try {
String newpath = "src/upload";
File directory = new File(newpath);
if (!directory.exists()) {
directory.mkdirs();
}
File fileawal = null;
File fileakhir = null;
String ext = this.filename.substring(filename.lastIndexOf('.')+1);
fileawal = new File(filename);
System.out.println(newpath);
fileakhir = new File(newpath+"/"+Nik.getText()+"."+ext);
System.out.println(fileakhir);
stat = koneksi.createStatement();
stat.executeUpdate("insert into user values ('" + Nik.getText() + "','" + Nama.getText() + "','" + fileakhir.toString() + "')");
System.out.println(fileakhir.toString());
JOptionPane.showMessageDialog(null, "Akun Sudah Terdaftar, Silahkan Kembali Login");
Files.copy(fileawal.toPath(), fileakhir.toPath());
Login log = new Login();
log.setVisible(true);
this.setVisible(false);
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
and this is the image picker button that i have
try {
JFileChooser chooser = new JFileChooser();
chooser.showOpenDialog(null);
File f = chooser.getSelectedFile();
ImageIcon icon = new ImageIcon(f.toString());
Image img = icon.getImage().getScaledInstance(Foto.getWidth(), Foto.getHeight(), Image.SCALE_DEFAULT);
ImageIcon ic = new ImageIcon(img);
Foto.setIcon(ic);
filename = f.getAbsolutePath();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
I have tried using .toString(), .getPath(), .getAbsolutePath(), but none of them include '/' in the database

Related

Saving images using dialogs in java FXML (java 8)

So im trying to save a image (Image class from javafx.scene.image.Image) onto a file with a save file dialog (JFileChooser) so that it is user friendly.
What i want it to do: Save the image specified
What it does: Save dialog works (i think), and it doesn't save (write to file) anything.
Here is the code behind it:
public void saveFile() { //menu item interface for save and save as
JFrame parentFrame = new JFrame();
JFileChooser fileChooser = new JFileChooser();
fileChooser.setDialogTitle("Save");
fileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));
//Setting the file extentions
/*fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("PNG Image", ".png"));
fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("JPG Image", ".jpg"));
fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("BMP Image", ".bmp"));*/
int userSelection = fileChooser.showSaveDialog(parentFrame);
if (userSelection == JFileChooser.APPROVE_OPTION) {
File fileToSave = fileChooser.getSelectedFile(); //selected file
saveToFile(picFrame.getImage(), fileToSave); //save the file
System.out.println("Save as file: " + fileToSave.getAbsolutePath()); //debug because it doesnt work
}
parentFrame.dispose();
}
and here is saveToFile
public static void saveToFile(Image image, File file) {
String extension = "";
File outputFile = file;
try {
if (file != null && file.exists()) {
String name = file.getName();
extension = name.substring(name.lastIndexOf("."));
}
} catch (Exception e) {
extension = "";
}
BufferedImage bImage = SwingFXUtils.fromFXImage(image, null);
try {
ImageIO.write(bImage, extension, outputFile);
System.out.println("Saveing file");
} catch (IOException e) {
throw new RuntimeException(e);
}
}
After some digging arround and debuging i found the problem and the solution , so here it is.
All the code.
public void saveFile() { //menu item interface for save and save as
Window mainStage = ap.getScene().getWindow(); //get ze window
FileChooser fileChooser = new FileChooser(); //Filechooser the class that has the file chooser
fileChooser.setTitle("Open Resource File"); //Title of prompt
fileChooser.getExtensionFilters().addAll( //add filter
new ExtensionFilter("Image Files", "*.png", "*.jpg", "*.gif", ".bmp"), //Filters
new ExtensionFilter("All Files", "*.*")); //Filters
File selectedFile = fileChooser.showSaveDialog(mainStage); //get the file
if (selectedFile != null) { //if something is selected then
System.out.println(selectedFile.getAbsoluteFile()); //debug
System.out.println(selectedFile.getAbsoluteFile().getParent()); //debug
Image img = SwingFXUtils.toFXImage(bImg, null); //convert to Image
saveToFile(img, selectedFile); //save the Image
}
}
/**
* A simple image save
*
* #param image The image you want to save
* #param file The file where you want to save it
*/
public static void saveToFile(Image image, File file) {
File outputFile = file; //file
BufferedImage bImage = SwingFXUtils.fromFXImage(image, null); //Convert to bufferedimage
try {
ImageIO.write(bImage, getFileExtension(outputFile).toUpperCase(), outputFile.getAbsoluteFile()); //actualy save
System.out.println("Saveing file ex: " + getFileExtension(outputFile).toUpperCase() + " to: " + outputFile.getAbsoluteFile() + " with name " + outputFile.getName());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private static String getFileExtension(File file) {
String name = file.getName();
int lastIndexOf = name.lastIndexOf(".") + 1;
if (lastIndexOf == -1) {
return ""; // empty extension
}
return name.substring(lastIndexOf);
}

Java Swing File and Folder Choose

Hi I am new to swing and I need some help. I have build a file processing project where I read an input file and some other existing files in the project, do many checks and parsing and produce a csv and an xlsx file. Until now I used for these inputs
JTextField csvpath = new JTextField();
JTextField csvfile = new JTextField();
JTextField xmlpath = new JTextField();
JTextField xmlfile = new JTextField();
JTextField excpath = new JTextField();
JTextField excfile = new JTextField();
Object[] message = {
"Enter the path of the CSV file to be created:", csvpath,
"Enter the CSV file name:", csvfile,
"Now enter the XML path to be read:", xmlpath,
"Also enter the XML file name:", xmlfile,
"Please enter the Excel file path to be created:", excpath,
"Finally enter the Excel file name:", excfile
};
int option = JOptionPane.showConfirmDialog(null, message, "Convert XML File to CSV File", JOptionPane.OK_CANCEL_OPTION);
if (option == JOptionPane.OK_OPTION) {
String csvPath = csvpath.getText();
String csvFileName = csvfile.getText();
String xmlPath = xmlpath.getText();
String xmlFileName = xmlfile.getText();
String excPath = excpath.getText();
String excFileName = excfile.getText();
String FullcsvPath = csvPath + "\\" + csvFileName + ".csv";
String FullxmlPath = xmlPath + "\\" + xmlFileName + ".xml";
String excelPath = excPath + "\\" + excFileName + ".xlsx";
.
.
parsing/creating starts...
Because in the future this project will be used by others I wanted to create file chooser and get the file/folder paths as strings in order to read the input and create etc...
I have created a class and public strings for paths and when I call it the program does not stop like before, continues to run while the Frame is open without getting the paths I want. My new class is:
public static void SelectFiles() throws ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException {
final JFrame window = new JFrame("Parse for manufacturers - Developed by Aris M");
JPanel topPanel = new JPanel();
JPanel midPanel = new JPanel();
JPanel botPanel = new JPanel();
final JButton openFolderChooser = new JButton("Select Folder to save csv - xlsx results");
final JButton openFileChooser = new JButton("Select the File to be parsed");
final JButton closeButton = new JButton("OK");
window.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
final JFileChooser fc = new JFileChooser();
openFolderChooser.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
fc.setCurrentDirectory(new java.io.File("user.home"));
fc.setDialogTitle("This is a JFileChooser");
fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
if (fc.showOpenDialog(openFolderChooser) == JFileChooser.APPROVE_OPTION) {
JOptionPane.showMessageDialog(null, fc.getSelectedFile().getAbsolutePath());
System.out.println(fc.getSelectedFile().getAbsolutePath());
csv = fc.getSelectedFile().getAbsolutePath();
xlsx = csv;
System.out.println(csv);
}
}
});
openFileChooser.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
fc.setCurrentDirectory(new java.io.File("user.home"));
fc.setDialogTitle("This is a JFileChooser");
fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
if (fc.showOpenDialog(openFileChooser) == JFileChooser.APPROVE_OPTION) {
JOptionPane.showMessageDialog(null, fc.getSelectedFile().getAbsolutePath());
System.out.println(fc.getSelectedFile().getAbsolutePath());
xml = fc.getSelectedFile().getAbsolutePath();
System.out.println(xml);
}
}
});
closeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
window.dispose();
}
});
window.add(BorderLayout.NORTH, topPanel);
window.add(BorderLayout.CENTER, midPanel);
window.add(BorderLayout.SOUTH, botPanel);
topPanel.add(openFolderChooser);
midPanel.add(openFileChooser);
botPanel.add(closeButton);
window.setSize(500, 150);
window.setVisible(true);
window.setLocationRelativeTo(null);
}
Swing code runs in separate thread known as the event dispatch thread. Just make your main thread busy while frame is visible. Add following code to the end of SelectFiles() method:
while (window.isVisible()) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}

Opening a file without the extension - Java

Im doing a project for my college, my save/opening file are working all right, but I need them to save as my desired extension, and open like that as well.
For example: When I click on Save File, I write the name testFile as file name and hit save, now the my code must save as my desired extension. Same works for opening file, if I write testFile and hit open, it must locate the testFile.txt. Anyone can give me a hand how I should do this? follow my code below.
private class SalvaDesenho implements ActionListener {
private Component parent;
SalvaDesenho(Component parent) {
this.parent = parent;
}
public void actionPerformed(ActionEvent e) {
try {
final JFileChooser fc = new JFileChooser();
fc.setFileFilter(new FileNameExtensionFilter("Arquivo de Texto (.txt)", "txt"));
fc.setAcceptAllFileFilterUsed(false);
int returnVal = fc.showSaveDialog(parent);
if (returnVal != JFileChooser.APPROVE_OPTION)
return;
int op = 0;
if (fc.getSelectedFile().exists()) {
Object[] options = { "Sim", "Não" };
op = JOptionPane.showOptionDialog(null, "O arquivo já existe deseja substituilo?", "Warning",
JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE,
null, options, options[1]);
}
if (op != 0) return;
System.out.println("Salvando: " + fc.getSelectedFile().getPath());
FileOutputStream fout = new FileOutputStream(fc.getSelectedFile());
ObjectOutputStream oos = new ObjectOutputStream(fout);
oos.writeObject(figuras);
isSaved = true;
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
private class AbreDesenho implements ActionListener {
private Component parent;
AbreDesenho(Component parent) {
this.parent = parent;
}
public void actionPerformed(ActionEvent e) {
try {
final JFileChooser fc = new JFileChooser();
FileNameExtensionFilter txtFilter = new FileNameExtensionFilter("Arquivo de texto (.txt)", "txt");
fc.setFileFilter(txtFilter);
int returnVal = fc.showOpenDialog(parent);
if (returnVal != JFileChooser.APPROVE_OPTION)
System.out.println("File error!");
System.out.println("Abrindo: " + fc.getSelectedFile().getPath());
FileInputStream fin = new FileInputStream(fc.getSelectedFile());
ObjectInputStream ois = new ObjectInputStream(fin);
figuras = (Vector<Figura>) ois.readObject();
} catch (Exception ex) {
ex.printStackTrace();
return;
}
pnlDesenho.getGraphics().clearRect(0 , 0, parent.getHeight(), parent.getWidth());
for (int i=0 ; i<figuras.size(); i++)
figuras.get(i).torneSeVisivel(pnlDesenho.getGraphics());
}
}
Thanks.
You have to do this manually:
Get the File object from the JFileChooser
Get its absolute path as a String, using getAbsolutePath().
Check whether it has an extension or not: Check file extension in Java
If not, add your extension to the path: path = path+".txt";
Create a new File object from the path: File file = new File(path)
Open/Save the file (your code)

Append Images to RTF document

I am trying to add images to a rtf document. I am able to add images to the document but I can't append any images. This means that when the 2nd Image is added, the first image is removed. I think that whenever the code is executed a new rtf document is created.
public class InsertToWord {
com.lowagie.text.Document doc = null;
FileOutputStream evidenceDocument;
String fileName = "evidenceDocument.rtf";
settings obj = null;
InsertToWord() {
obj = new settings();
doc = new com.lowagie.text.Document();
}
public void insertImage(File saveLocation) {
try {
evidenceDocument = new FileOutputStream(obj.getFileLocation() + fileName);
RtfWriter2.getInstance(doc, evidenceDocument);
doc.open();
com.lowagie.text.Image image = com.lowagie.text.Image.getInstance(saveLocation.toString());
image.scaleAbsolute(400, 300);
doc.add(image);
doc.close();
} catch (Exception e) {
}
}
}
On your insertImage() method, you are indeed creating a new file and overwriting your old one.
This line is creating the new file:
evidenceDocument = new FileOutputStream(obj.getFileLocation()+fileName);
You can pass the FileOutputStream in as a parameter to the method and then remove the line all together:
public void insertImage( FileOutputStream evidenceDocument , File saveLocation )
This code is the one I´m using to add an image into a RTF format and its working fine :
public void actionPerformed(ActionEvent arg0) {
JFileChooser fileChooser = new JFileChooser();
int option = fileChooser.showOpenDialog(null);
File file = fileChooser.getSelectedFile();
if (option == JFileChooser.APPROVE_OPTION) {
try {
BufferedImage image = ImageIO.read(file);
image = Scalr.resize(image, 200);
document = (StyledDocument) textPane.getDocument();
javax.swing.text.Style style = document.addStyle("StyleName", null);
StyleConstants.setIcon(style, new ImageIcon(image));
document.insertString(document.getLength(), "ignored text", style);
}
catch (Exception e) {
e.printStackTrace();
}
}
if (option == JFileChooser.CANCEL_OPTION) {
fileChooser.setVisible(false);
}
}// End of Method
The textPane variable is a JTextPane.

Unable to figure how to store "Save As" text in a string and use it

I am new to UI design in Java. I am trying to create a GUI to download a file off the Internet and save it on your hard drive. I have got the code working except for one thing which I want to add. I have added a JFileChooser which lets the user select the destination folder. But I am unable to figure out how to change the filename to the one which user enters in the Save As bar on the JFileChooser menu.
Browse Button
browseButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
chooser = new JFileChooser();
chooser.setCurrentDirectory(null);
chooser.setDialogTitle("Select folder to save");
chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
chooser.setAcceptAllFileFilterUsed(true);
//chooser.showDialog(downloadButton, "Save");
if(chooser.showSaveDialog(downloadButton) == JFileChooser.APPROVE_OPTION)
{
System.out.println("The location to save is: " + chooser.getCurrentDirectory());
DESTINATION_FOLDER = chooser.getCurrentDirectory().toString();
}
}
});
Download Button
URLConnection connection = downloadUrl.openConnection();
input = new BufferedInputStream(connection.getInputStream());
output = new FileOutputStream(DESTINATION_FOLDER + "/" + filename);
Here filename should be the one which user enters. Pointers on how to get this done?
Actually you don't need to get the FileName from the Save As Bar in the JFileChooser.
Just do like this:
browseButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
chooser = new JFileChooser();
chooser.setCurrentDirectory(null);
chooser.setDialogTitle("Select folder to save");
//Don't use the 'FileSelectionMode();'. Let it be Default.
chooser.setAcceptAllFileFilterUsed(true);
if(chooser.showSaveDialog(downloadButton) == JFileChooser.APPROVE_OPTION)
{
file = chooser.getSelectedFile();
//file should be declared as a File.
System.out.println("The location to save is: " + chooser.getCurrentDirectory();));
System.out.println("The FileName is: " + file.getName());
}
}
DOWNLOAD BUTTON:
URLConnection connection = downloadUrl.openConnection();
input = new BufferedInputStream(connection.getInputStream());
output = new FileOutputStream(file);
Without seeing more of your code the best I could suggest is to create a Global String in the class you are working in.
public class gui extends JFrame{
public String filePath="";
public static void main(String args[]){
//button code
browseButton.addActionListener(new ActionListener())
saveAsButton.addActionListener(new ActionListener())
URLConnection connection = downloadUrl.openConnection();
}
public void actionPerformed(ActionEvent e)
{
if (e.getActionCommand().equals("browseButton"){
chooser = new JFileChooser();
chooser.setCurrentDirectory(null);
chooser.setDialogTitle("Select folder to save");
chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
chooser.setAcceptAllFileFilterUsed(true);
//chooser.showDialog(downloadButton, "Save");
if(chooser.showSaveDialog(downloadButton) == JFileChooser.APPROVE_OPTION)
{
System.out.println("The location to save is: "+chooser.getCurrentDirectory());
filePath = chooser.getCurrentDirectory().toString();
}
else{
//save as button selected
input = new BufferedInputStream(connection.getInputStream());
output = new FileOutputStream(filePath);
}
}
}
Add this line:
chooser.setDialogType(JFileChooser.SAVE_DIALOG);
Full code:
browseButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
chooser = new JFileChooser();
chooser.setCurrentDirectory(null);
chooser.setDialogTitle("Select folder to save");
chooser.setDialogType(JFileChooser.SAVE_DIALOG);
chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
chooser.setAcceptAllFileFilterUsed(true);
//chooser.showDialog(downloadButton, "Save");
if(chooser.showSaveDialog(downloadButton) == JFileChooser.APPROVE_OPTION)
{
System.out.println("The location to save is: " + chooser.getCurrentDirectory());
DESTINATION_FOLDER = chooser.getCurrentDirectory().toString();
}
}

Categories