delete image from the folder - java

I want to delete one image from the folder when I delete a user from the table with this image. Here is my code:
//first I can the function that finds a path of the image in the folder
public void deleteStudent(String name) {
try {
CallableStatement statement = null;
Connection data = getmyConnection();
statement = data.prepareCall("{call delete_student(?)}");
statement.setString(1, name);
//statement.registerOutParameter(2, java.sql.Types.VARCHAR);
statement.executeQuery();
} catch (Exception c) {
c.printStackTrace();
}
//After I call the function to delete image from directory
deleteImageDerictory(name);
}
This method allows choosing the image from the directory when I get the image I add the path in jTextField1.getText().
//use this method to get the path of my image.
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser file = new JFileChooser();
file.setCurrentDirectory(new File(System.getProperty("user.home")));
FileNameExtensionFilter filter = new FileNameExtensionFilter("*.Images", "jpeg", "jpg", "png");
file.addChoosableFileFilter(filter);
int result = file.showSaveDialog(null);
if(result ==JFileChooser.APPROVE_OPTION) {
File selectedFile = file.getSelectedFile();
//GET ABSOLUTE PATH OF PICTURES
jTextField1.setText(selectedFile.getAbsolutePath());
//addPicture.setText(selectedFile.getName());
//GET NAME OF PICTURES
//getPicName = selectedFile.getName();
} else if(result == JFileChooser.CANCEL_OPTION) {
System.out.println("File not found!");
}
}
//I use this method to call another method deleteImageDerictory(jTextField1.getText());
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try{
deleteImageDerictory(jTextField1.getText());
}catch(Exception e) {
e.printStackTrace();
}
}
public void deleteImageDerictory(String name) {
String pictureName = null;
try {
CallableStatement statement = null;
Connection data = getmyConnection();
statement = data.prepareCall("{call get_picture(?)}");
statement.setString(1, name);
//statement.registerOutParameter(2, java.sql.Types.VARCHAR);
myResults = statement.executeQuery();
while (myResults.next()) {
//COPY PATH IN pictureName
pictureName = myResults.getString(1);
}
myResults.close();
} catch (Exception c) {
c.printStackTrace();
}
//DELETE ELEMENT FROM FOLDER
File sourceFile = new File(pictureName);
File file = new File("/Computer/NetBeans IDE 8.2/NewDataBase/src/newdatabase/images/");
images = file.listFiles();
File file2 = new File(file.getAbsolutePath(), sourceFile.getName() );
boolean deleted = file2.delete();
System.out.println(deleted);
}
I just don't know how to delete image from folder when I find it. Any ideas?

You can use the modern and more powerful java.nio.* instead of the old fashioned java.io.File. You just have to create a Path object containing the path to the folder where the images are stored and resolve the file name:
//DELETE ELEMENT FROM FOLDER
Path imagesPath = Paths.get(
"/Computer/NetBeans IDE 8.2/NewDataBase/src/newdatabase/images/" +
pictureName);
try {
Files.delete(imagesPath);
System.out.println("File "
+ imagesPath.toAbsolutePath().toString()
+ " successfully removed");
} catch (IOException e) {
System.err.println("Unable to delete "
+ imagesPath.toAbsolutePath().toString()
+ " due to...");
e.printStackTrace();
}
EDIT due to discussion in comments below:
This is a very simple approach that deletes a file chosen via JFileChooser:
public static void main(String[] args) {
JFileChooser jfc = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory());
int result = jfc.showOpenDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
File selectedFile = jfc.getSelectedFile();
System.out.println("Chosen file: " +
selectedFile.getAbsolutePath() +
" will be deleted!");
Path pathToBeDeleted = Paths.get(selectedFile.getAbsolutePath());
try {
Files.delete(pathToBeDeleted);
} catch (IOException e) {
e.printStackTrace();
}
}
}
I have just tried it myself and it successfully removes the chosen file.

public static void main(String[] args) {
JFileChooser jfc = new JFileChooser(FileSystemView.getFileSystemView()./0());
int result = jfc.showOpenDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
File selectedFile = jfc.getSelectedFile();
System.out.println("Chosen file: " +
selectedFile.getAbsolutePath() +
" will be deleted!");
Path data= Paths.get(selectedFile.getAbsolutePath());
try {
Files.delete(data);
} catch (Exception e) {
e.printStackTrace();
}
}
}

Related

Java reset for loop so file can be read from the beggining in infinite loop

I have methods to read file and check for extension
//using FileChooser to select folder we want to get photos from
static final File dir = new File("D:\\Pictures\\NatGeoPaper2020\\3\\");
//array of supported extensions
static final String[] EXTENSIONS = new String[]{"jpg", "jpeg", "png"};
//filter to identify images by extensions
static final FilenameFilter IMAGE_FILTER = new FilenameFilter() {
#Override
public boolean accept(final File dir, final String name) {
for (final String ext : EXTENSIONS) {
if (name.endsWith("." + ext)) {
return true;
}
}
return (false);
}
};
In main I invoke those methods - basically read all images and show as slideshow to user.
if (dir.isDirectory()) {
for (final File f : dir.listFiles(IMAGE_FILTER)) {
BufferedImage img = null;
try {
img = ImageIO.read(f);
SPI.INSTANCE.SystemParametersInfo(
new UINT_PTR(SPI.SPI_SETDESKWALLPAPER),
new UINT_PTR(0),
dir + "/" + f.getName(),
new UINT_PTR(SPI.SPIF_UPDATEINIFILE | SPI.SPIF_SENDWININICHANGE));
Thread.sleep(6000);
} catch (final IOException e) {
throw new Error(e);
}
}
}
Now my problem is, how can I "reset" my for loop in main to achieve infinite loop? I just want to change wallpaper every 6 seconds infinitely, withour rerunning a program.
Put a while(true) loop around it.
You can do it as follows:
if (dir.isDirectory()) {
while(true) {
for (final File f : dir.listFiles(IMAGE_FILTER)) {
BufferedImage img = null;
try {
img = ImageIO.read(f);
SPI.INSTANCE.SystemParametersInfo(
new UINT_PTR(SPI.SPI_SETDESKWALLPAPER),
new UINT_PTR(0),
dir + "/" + f.getName(),
new UINT_PTR(SPI.SPIF_UPDATEINIFILE | SPI.SPIF_SENDWININICHANGE));
Thread.sleep(6000);
} catch (final IOException e) {
throw new Error(e);
}
}
}
}

Cant delete a file after editing it with zip4j (Java)

I am trying to copy a jar file into an other jarfile.
so to get them together i unzip both to Infect.BIND_TMP.
After that i go ahead and delete "first" but here Comes the Problem:
I get "false" returned by file.delete();
Did i not Close all streams? I can't find the error... :c
mainFile(); just Returns the MainClass from the MANIFEST.MF jarFile
public static boolean bindJarFiles(File first, File second) {
try {
File tmp_bind = new File(Infect.TMP_BIND);
if (tmp_bind.exists()) {
tmp_bind.delete();
tmp_bind.mkdirs();
} else {
tmp_bind.mkdirs();
}
tmp_bind = null;
ZipFile m = new ZipFile(first);
ZipFile g = new ZipFile(second);
if (InfectUtils.infected(second))
return false;
g.extractAll(Infect.TMP_BIND);
#SuppressWarnings("unchecked")
List<FileHeader> fileHeaders = m.getFileHeaders();
for (FileHeader fileHeader : fileHeaders) {
if (fileHeader.isDirectory() && fileHeader.getFileName().equals(superPackageNameFromFile())) {
g.extractFile(fileHeader, Infect.TMP_BIND);
}
if (fileHeader.isDirectory() && fileHeader.getFileName().equals("META-INF")) {
g.extractFile(fileHeader, Infect.TMP_BIND);
}
}
PrintWriter pw = new PrintWriter(new File(Infect.TMP_BIND_FILES_TXT));
pw.println(mainFile(second));
pw.println("_-$-_" + superPackageNameFromFile());
pw.flush();
pw.close();
// Reset all the open Streams etc
String p = second.getAbsolutePath();
g = null;
if (!second.delete()) {
System.err.println("Cannot delete File!");
}
g = new ZipFile(p);
ZipParameters params = new ZipParameters();
params.setIncludeRootFolder(false);
params.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
params.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
g.createZipFile(new File(Infect.TMP_BIND), params);
} catch (ZipException | FileNotFoundException e) {
e.printStackTrace();
return false;
}
return true;
}

Java FTP using Apache commons throws "IOException caught while copying"

I have made a JavaFX application which includes uploading large files (> 1GB) to a server. Every time I got the same error on same place. Any Suggestions what am I doing wrong here.
ftpclient.connect(server, port);
ftpclient.login(ftpuser, ftppass);
ftpclient.enterLocalPassiveMode();
ftpclient.setKeepAlive(true);
ftpclient.setControlKeepAliveTimeout(3000);
Task<Void> copyMnt = new Task<Void>() {
#Override
protected Void call(){
try {
new Thread(new FTPHandler(ftpclient, source , dest)).run();
} catch (IOException ex) {
Logger.getLogger(MyAppController.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
};
new Thread(copyMnt).start();
Now on the FTPHandler Class
// The constructor will set the ftpclient, source and destinations.
#Override
public void run() {
try {
uploadDirectory(this.getClient(), this.getDest(), this.getSrc(), "");
} catch (IOException ex) {
Logger.getLogger(FTPHandler.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static void uploadDirectory(FTPClient ftpClient,
String remoteDirPath, String localParentDir, String remoteParentDir)
throws IOException {
File localDir = new File(localParentDir);
File[] subFiles = localDir.listFiles();
if (subFiles != null && subFiles.length > 0) {
for (File item : subFiles) {
String remoteFilePath = remoteDirPath + "/" + remoteParentDir
+ "/" + item.getName();
if (remoteParentDir.equals("")) {
remoteFilePath = remoteDirPath + "/" + item.getName();
}
if (item.isFile()) {
// upload the file
String localFilePath = item.getAbsolutePath();
java.util.Date date= new java.util.Date();
System.out.println(new Timestamp(date.getTime()) + " : Uploading :: " + localFilePath + " to " + remoteFilePath);
boolean uploaded = uploadSingleFile(ftpClient,
localFilePath, remoteFilePath);
if (uploaded) {
System.out.println("Success : "
+ remoteFilePath);
} else {
System.out.println("Failed : "
+ localFilePath);
}
} else {
// create directory on the server
boolean created = ftpClient.makeDirectory(remoteFilePath);
if (created) {
System.out.println("CREATED the directory: "
+ remoteFilePath);
} else {
System.out.println("COULD NOT create the directory: "
+ remoteFilePath);
}
// upload the sub directory
String parent = remoteParentDir + "/" + item.getName();
if (remoteParentDir.equals("")) {
parent = item.getName();
}
localParentDir = item.getAbsolutePath();
uploadDirectory(ftpClient, remoteDirPath, localParentDir,
parent);
}
}
}
}
Every time I am uploading the files (files are of different types like .iso, .dat etc), The first few files (upload sequence is like first few hundred files are smaller i.e less than few MBs then Last 10 files are more than 1 GB big)will be successfully uploaded (i.e all smaller files and 2 of the last 10 files) but when it starts uploading the third big file I get following exception.
SEVERE: null
org.apache.commons.net.io.CopyStreamException: IOException caught while copying.
at org.apache.commons.net.io.Util.copyStream(Util.java:134)
at org.apache.commons.net.ftp.FTPClient._storeFile(FTPClient.java:653)
at org.apache.commons.net.ftp.FTPClient.__storeFile(FTPClient.java:624)
at org.apache.commons.net.ftp.FTPClient.storeFile(FTPClient.java:1976)
The CopyStreamException has a "cause" exception. Check that using the .getCause(), to see what went wrong.
See the Util.copyStream method:
public static final long copyStream(InputStream source, OutputStream dest,
int bufferSize, long streamSize,
CopyStreamListener listener,
boolean flush)
throws CopyStreamException
{
int bytes;
long total = 0;
byte[] buffer = new byte[bufferSize >= 0 ? bufferSize : DEFAULT_COPY_BUFFER_SIZE];
try
{
while ((bytes = source.read(buffer)) != -1)
{
....
}
}
catch (IOException e)
{
throw new CopyStreamException("IOException caught while copying.",
total, e);
}
return total;
}
Somewhere in your uploadSingleFile function, do
try
{
ftpClient.storeFile(...)
}
catch (Exception e)
{
e.printStackTrace();
if (e.getCause() != null)
{
e.getCause().printStackTrace();
}
}
I do not know Java, so the code may not be 100% correct.
See also Getting full string stack trace including inner exception.

"<identifier> expected" when creating class from template

I have a bot I am creating that can take input from an IRC channel to create new classes for the bot to use when running. However, when it tries to compile the class, it results in an "identifier expected" error at the class name. However, if I type up a class which is identical to that created by the bot using the template, it compiles without issue. Below are the 3 methods used for this process:
//Create basic command
public static int writeBasicCommand(String trigger, String output, boolean edit) {
int success = 0, existenceError = 1, unknownError = 2;
try {
String filePath = "C:/commands/" + trigger + ".java"; //Location for new class
File file = new File(filePath);
//Check if command exists
if (file.exists()) {
if(!edit) {
return existenceError;
}
} else if(edit) {
return existenceError;
}
//Grab and modify template
String template = readFile("C:/template.txt");
String namedCom = template.replace("--COMMANDNAME--", trigger);
String content = namedCom.replace("--COMMANDRESULT--", "\"" + output + "\"");
//Write command
WriteFile(content, file, false);
if (Compile(filePath)==true) {
System.out.println("Done");
return success;
} else {
return unknownError;
}
} catch (IOException e) {
e.printStackTrace();
return unknownError;
}
}
//Compile new commands
public static boolean Compile(String fileToCompile) {
System.setProperty("java.home", "C:\\Program Files\\Java\\jdk1.7.0_11");
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
int compilationResult = compiler.run(null, null, null, fileToCompile);
if(compilationResult == 0) {
System.out.println("Compilation is successful");
return true;
} else {
System.out.println("Compilation Failed");
if ((new File(fileToCompile).exists())) {
new File(fileToCompile).delete();
}
return false;
}
}
//Write to a file
public static boolean WriteFile(String fileContents, File destination, boolean append) {
try {
// if file doesnt exist, then create it
if (!destination.exists()) {
destination.createNewFile();
}
FileWriter fw = new FileWriter(destination.getAbsoluteFile(), append);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(fileContents);
bw.close();
fw.close();
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}

Make name to PDF with JFileChooser

i use this code to save a pdf file on desktop from Mysql, but the file saved without extension, how can i save it automatcly with extension pdf, ?!!
JFileChooser JFileChooser = new JFileChooser(".");
Activiter ac = new Activiter();
int status = JFileChooser.showDialog(null,"Saisir l'emplacement et le nom du fichier cible");
if(status == JFileChooser.APPROVE_OPTION)
{
try
{
ac.chargeIMG(jTable3.getValueAt(rec, 6).toString(),JFileChooser.getSelectedFile().getAbsolutePath());
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(null,"Une erreur s'est produite dans le chargement de documents.");
ex.printStackTrace();
}
}
thanks for Help,
methode chargerIMG that colled by ac.chargeIMG
chargeIMG is give the pdf file from MySQL, the code is
public void chargeIMG(String idpro, String location) throws Exception
{
// cnx
File monImage = new File(location);
FileOutputStream ostreamImage = new FileOutputStream(monImage);
try {
PreparedStatement ps = conn.prepareStatement("SELECT img FROM projet WHERE idpro=?");
try
{
ps.setString(1,idpro);
ResultSet rs = ps.executeQuery();
try
{
if(rs.next())
{
InputStream istreamImage = rs.getBinaryStream("img");
byte[] buffer = new byte[1024];
int length = 0;
while((length = istreamImage.read(buffer)) != -1)
{
ostreamImage.write(buffer, 0, length);
}
}
}
finally
{
rs.close();
}
}
finally
{
ps.close();
}
}
finally
{
ostreamImage.close();
}
}
Override getSelectedFile():
import java.io.File;
import javax.swing.JFileChooser;
public class MyFileChooser extends JFileChooser
{
private static final long serialVersionUID = 1L;
private String extension;
public MyFileChooser(String currentDirectoryPath, String extension)
{
super(currentDirectoryPath);
this.extension = extension;
}
#Override
public File getSelectedFile()
{
File selectedFile = super.getSelectedFile();
if(selectedFile != null && (getDialogType() == SAVE_DIALOG || getDialogType() == CUSTOM_DIALOG))
{
String name = selectedFile.getName();
if(!name.contains(".")) selectedFile = new File(selectedFile.getParentFile(), name + "." + extension);
}
return selectedFile;
}
}
and then use it like:
JFileChooser chooser = new MyFileChooser(".", "pdf");
The simplest solution, obtain the path (File.getPath), check if it ends by the expected extension and if not then replace it by another File with the extension present: new File(path+".pdf");

Categories