/* http-cm - File management extensions to jdk.httpserver Copyright (C) 2021 Ulrich Hilger This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see . */ package de.uhilger.httpserver.cm.actor; import de.uhilger.httpserver.cm.OrdnerBearbeiter; import static de.uhilger.httpserver.cm.FileManager.OP_DELETE; import static de.uhilger.httpserver.cm.FileManager.STR_DOT; import de.uhilger.httpserver.image.ImageActor; import java.io.File; import java.io.IOException; import java.nio.file.DirectoryStream; import java.nio.file.Files; import java.nio.file.Path; import java.util.List; /** * Eine Klasse mit Methoden zum Loeschen von Dateien * * @author Ulrich Hilger, 15. Januar 2024 */ public class Eraser { public String deleteFiles(String relPath, List fileNames, String base) { String result = null; try { //logger.fine(fileNames.toString()); if (!relPath.startsWith(STR_DOT)) { File targetDir = new File(base, relPath); // getTargetDir(relPath); //logger.fine("targetDir: " + targetDir); for (String fileName : fileNames) { File targetFile = new File(targetDir, fileName); //logger.fine(targetFile.getAbsolutePath()); if (targetFile.isDirectory()) { OrdnerBearbeiter bearbeiter = new OrdnerBearbeiter(); bearbeiter.setOperation(OP_DELETE); Files.walkFileTree(targetFile.toPath(), bearbeiter); } else { /* Wenn targetFile mit jpg, jpeg oder png endet, muss eine Unterfunktion eine Liste aller Dateien bilden, die so heissen, also z.B. alle [Dateiname]*.jpg */ String fname = targetFile.getName().toLowerCase(); if (fname.endsWith(ImageActor.JPEG) || fname.endsWith(ImageActor.JPG) || fname.endsWith(ImageActor.PNG)) { deleteImgFiles(targetDir, targetFile); } else { targetFile.delete(); } } } result = "deleted"; } } catch (IOException ex) { //logger.log(Level.SEVERE, ex.getLocalizedMessage(), ex); } return result; } private void deleteImgFiles(File targetDir, File targetFile) throws IOException { String fnameext = targetFile.getName(); int dotpos = fnameext.lastIndexOf(STR_DOT); String fname = fnameext.substring(0, dotpos); String ext = fnameext.substring(dotpos); //logger.fine("fname: " + fname + ", ext: " + ext); DirectoryStream stream = Files.newDirectoryStream(targetDir.toPath(), fname + "*" + ext); //"*.{txt,doc,pdf,ppt}" for (Path path : stream) { //logger.fine(path.getFileName().toString()); Files.delete(path); } stream.close(); } }