Java delete and rename file issue - java

Method below has function to simply move files from the "working" to the "move" directory which paths it receives through the method call. It all works, but for the case when file name has name with two extensions (like .xml.md5) where the .renameTo method returns false. Is there a way to alter the below code so it would work regardless of the OS that it's run on. (Currently it is the Windows)
public void moveToDir(String workDir, String moveDir) throws Exception {
File tempFile = new File(workDir);
File[] filesInWorkingDir = tempFile.listFiles();
for (File file : filesInWorkingDir) {
System.out.println(file.getName());
if (new File(moveDir + File.separator + file.getName()).exists())
new File(moveDir + File.separator + file.getName()).delete();
System.out.println(moveDir + File.separator + file.getName());
Boolean renameSuccessful = file.renameTo(new File(moveDir + File.separator + file.getName()));
if (!renameSuccessful) throw new Exception("Can't move file to " + moveDir +": " + file.getPath());
}
}

I have simplified your code and added a check if delete was successful. Try it.
public void moveToDir(String workDir, String moveDir) {
for (File file : new File(workDir).listFiles()) {
System.out.println(file.getName());
final File toFile = new File(moveDir, file.getName());
if (toFile.exists() && !toFile.delete())
throw new RuntimeException("Cannot delete " + toFile);
System.out.println(toFile);
if (!file.renameTo(toFile))
throw new RuntimeException(
"Can't move file to " + moveDir +": " + file.getPath());
}
}

Related

File.createTempFile in Java getting Incompatible type error

Till now my code works fine where I am creating file in temporary directory and processing it.
But now I am trying to provide specific directory where I actually want to create xml file. So in method createTmpXmlFile
private static Path createTmpXmlFile(final String prefix) {
try {
log.info("Creating temporary file {}{}", prefix, XML_SUFFIX);
return Files.createTempFile(Paths.get(gleifZipFile), prefix, XML_SUFFIX);
} catch (IOException e) {
throw new IllegalStateException("Could not create tmp file at " + prefix + XML_SUFFIX + ". ", e);
}
}
I changed from
return Files.createTempFile(prefix, XML_SUFFIX);
to
return File.createTempFile(prefix, XML_SUFFIX, "/tmp/in");
and I get following error:
java: incompatible types: java.lang.String cannot be converted to java.io.File.
If I change the logic here then its affecting other method that are calling createTmpXmlFile method.
I really don't understand how to resolve this issue. Below is my code:
#Slf4j
public class InputCS implements Runnable {
public static final String XML_SUFFIX = ".xml";
#Value("${gleifdataimporter.file.dir}")
private String gleifZipFile;
private void processleifZipFile() {
final AtomicBoolean isInsideLeiRecord = new AtomicBoolean();
isInsideLeiRecord.set(false);
final StringBuilder currentLeiRecordXml = new StringBuilder();
try (FileSystem zipFs = FileSystems.newFileSystem(jobRunner.getInputZipPath(), null)) {
Path tmpXMLPath = xmlFileFromLeiZipFile(zipFs);
try (Stream<String> lines = Files.lines(tmpXMLPath)) {
AtomicInteger processedLinesCounter = new AtomicInteger();
AtomicInteger currentLineNumber = new AtomicInteger();
lines.sequential().forEach(handleLineAndIncrementLineNumber(isInsideLeiRecord, currentLeiRecordXml, processedLinesCounter, currentLineNumber));
log.info("{} lines of XML file inside LEIF input ZIP file {} processed.", processedLinesCounter.get(), jobRunner.getInputZipPath());
}catch (IOException e) {
throw new IllegalStateException("Problem reading input file at " + jobRunner.getInputZipPath() + ".", e);
} finally {
Files.delete(tmpXMLPath);
}
} catch (IOException e) {
throw new IllegalStateException("Problem reading input file at " + jobRunner.getInputZipPath() + ".", e);
}
}
private Path xmlFileFromLeiZipFile(FileSystem zipFs) { //extracts the xml file from zip file
log.info("Input file {} exists: {}", jobRunner.getInputZipPath(), Files.exists(jobRunner.getInputZipPath()));
Path tmpXmlPath = createTmpXmlFile("leif__" + System.currentTimeMillis());
for (Path rootDir : zipFs.getRootDirectories()) {
try (Stream<Path> files = treeAt(rootDir)) {
log.info("Trying to extract LEIF XML file from ZIP file into {}.", tmpXmlPath);
final Path xmlFileInsideZip = files
.filter(isNotADir())
.filter(Files::isRegularFile)
.findFirst()
.orElseThrow(() -> new IllegalStateException("No file found in LEI ZIP file."));
log.info("Path to LEIF XML file inside ZIP file: {}.", xmlFileInsideZip);
return copyReplacing(xmlFileInsideZip, tmpXmlPath);
}
}
throw new IllegalStateException("No file found in LEI ZIP file " + jobRunner.getInputZipPath() + ".");
}
private static Path createTmpXmlFile(final String prefix) {
try {
log.info("Creating temporary file {}{}", prefix, XML_SUFFIX);
return Files.createTempFile(Paths.get(gleifZipFile), prefix, XML_SUFFIX);
} catch (IOException e) {
throw new IllegalStateException("Could not create tmp file at " + prefix + XML_SUFFIX + ". ", e);
}
}
#NotNull
private static Path copyReplacing(Path from, Path to) {
requireNonNull(from, "Trying to copy from a path, which is null to path " + to + "."); //trying to copy file where no xml file exist in root directory
requireNonNull(to, "Trying to copy from path " + from + " to a path, which is null.");
try {
return Files.copy(from, to, REPLACE_EXISTING);
} catch (IOException e) {
throw new IllegalStateException("Cannot copy from " + from + " to " + to + ". ", e);
}
}
}
As suggested by Slaw, use Files#createTempFile(Path,String,String,FileAttribute...) to specify the directory to create temp file.
Use Paths#get(String,String...) for java 7 or 8, or Path#of(String,String...) for java 11 or later to convert String to Path. Further reading: Paths.get vs Path.of
private static Path createTmpXmlFile(final String prefix) {
try {
// Java 11 or later
// return Files.createTempFile(Path.of("/tmp/in"), prefix, XML_SUFFIX);
// Java 8
return Files.createTempFile(Paths.get("/tmp/in"), prefix, XML_SUFFIX);
} catch (IOException e) {
throw new IllegalStateException("Could not create tmp file at " + prefix + XML_SUFFIX + ". ", e);
}
}
File.createTempFile is expecting a File object as third parameter. Just wrap your "/tmp/in" into a File
=> return File.createTempFile(prefix, XML_SUFFIX, new File("/tmp/in")); and you should be good to go.
so you can do:
File.createTempFile("prefix", "suffix", new File("/tmp/in"));
Or using NIO (recommended)
Files.createTempFile(Paths.get("/tmp/in"), "prefix", "suffix");

Can't remove or rename file

I am trying to remove the last line of a CVS file, to do so I need to rename / delete my input file, I tried several things, but I can't get it to work, this is what I got now:
File inputFile = new File((file.getParent() + "/ExportLijst " + dateFormat.format(date) + ".csv"));
inputFile.setWritable(true, true);
File f = (inputFile);
if (!f.exists())
throw new IllegalArgumentException(
"Delete: no such file or directory: " + inputFile);
if (!f.canWrite())
throw new IllegalArgumentException("Delete: write protected: "
+ inputFile);
if (f.isDirectory()) {
String[] files = f.list();
if (files.length > 0)
throw new IllegalArgumentException(
"Delete: directory not empty: " + inputFile);
}
boolean success = f.renameTo(removeFile);
if (!success)
throw new IllegalArgumentException("Delete: deletion failed");
I also tried this, with no result:
public void forceRename(File source, File target) throws IOException
{
if (target.exists())
target.delete();
source.renameTo(target);
}
Most likely you did not close the file, and then the other file operations will not do on Windows.
The code snippets you have put together for us, are in this way not very coherent - of course.
They look fine, though one would need to see the context. A bit much.
So try ensuring a close:
try (PrintWriter csvOut = ...) {
...
} // Automatic close

How to upload file using java ?

Hello i m trying to upload file using java file.. but i don't get it.. i get file size=0 i'm providing here my java code. tell me why i cant upload on particular folder. i want to store my file in particular folder. i am trying to get file size, file name but i got the null value where am i wrong please tell me.
public void updateTesti(ActionRequest actionRequest,ActionResponse actionResponse) throws IOException, PortletException
{
//image upload logic
String folder_for_upload =(getPortletContext().getRealPath("/"));
//String folder=actionRequest.getParameter("uploadfolder");
realPath=getPortletContext().getRealPath("/");
logger.info("RealPath is" + realPath);
logger.info("Folder is :" + folder_for_upload);
try
{
logger.info("Admin is try to upload");
UploadPortletRequest uploadRequest = PortalUtil.getUploadPortletRequest(actionRequest);
if (uploadRequest.getSize("fileName") == 0) {
SessionErrors.add(actionRequest, "error");
}
String sourceFileName = uploadRequest.getFileName("fileName");
File uploadedFile = uploadRequest.getFile("fileName");
System.out.println("Size of uploaded file: " + uploadRequest.getSize("fileName"));
logger.info("Uploded file name is: " + uploadRequest.getFileName("fileName"));
String destiFolder=("/home/ubuntu/liferay/liferay-portal-6.1.1-ce-ga2/tomcat-7.0.27/webapps/imageUpload-portlet/image");
String newsourcefilename = (uploadRequest.getFileName("fileName"));
File newFile = new File(destiFolder +"/"+ newsourcefilename);
logger.info("New file name: " + newFile.getName());
logger.info("New file path: " + newFile.getPath());
InputStream in = new BufferedInputStream(uploadRequest.getFileAsStream("fileName"));
FileInputStream fis = new FileInputStream(uploadedFile);
FileOutputStream fos = new FileOutputStream(newFile);
byte[] bytes_ = FileUtil.getBytes(in);
int i = fis.read(bytes_);
while (i != -1) {
fos.write(bytes_, 0, i);
i = fis.read(bytes_);
}
fis.close();
fos.close();
Float size = (float) newFile.length();
System.out.println("file size bytes:" + size);
System.out.println("file size Mb:" + size / 1048576);
logger.info("File created: " + newFile.getName());
SessionMessages.add(actionRequest, "success");
}
catch (FileNotFoundException e)
{
System.out.println("File Not Found.");
e.printStackTrace();
SessionMessages.add(actionRequest, "error");
}
catch (NullPointerException e)
{
System.out.println("File Not Found");
e.printStackTrace();
SessionMessages.add(actionRequest, "error");
}
catch (IOException e1)
{
System.out.println("Error Reading The File.");
SessionMessages.add(actionRequest, "error");
e1.printStackTrace();
}
}
You need to do this to upload small files < 1kb
File f2 = uploadRequest.getFile("fileupload", true);
They are stored in memory only. I have it in my catch statement incase I get a null pointer - or incase my original file (f1.length) == 0
I have executed your code.It is working as per expectation.There might be something wrong in your jsp page.I am not sure but might be your name attribute is not same as the one which you are using in processAction(assuming that you are using portlet).Parameter is case sensitive,so check it again.
You will find more on below link.It has good explanation in file upload.
http://www.codeyouneed.com/liferay-portlet-file-upload-tutorial/
I went through a file upload code, and when i implement that in my local system what i got is, portlet is saving the file i upload in tomcat/webbapp/abc_portlet_project location, what i dont understand is from where portlet found
String folder = getInitParameter("uploadFolder");
String realPath = getPortletContext().getRealPath("/");
System.out.println("RealPath" + realPath +"\\" + folder); try {
UploadPortletRequest uploadRequest =
PortalUtil.getUploadPortletRequest(actionRequest);
System.out.println("Size: "+uploadRequest.getSize("fileName"));
if (uploadRequest.getSize("fileName")==0)
{SessionErrors.add(actionRequest, "error");}
String sourceFileName = uploadRequest.getFileName("fileName"); File
file = uploadRequest.getFile("fileName");
System.out.println("Nome file:" +
uploadRequest.getFileName("fileName")); File newFolder = null;
newFolder = new File(realPath +"\" + folder);
if(!newFolder.exists()){ newFolder.mkdir(); }
File newfile = null;
newfile = new File(newFolder.getAbsoluteFile()+"\"+sourceFileName);
System.out.println("New file name: " + newfile.getName());
System.out.println("New file path: " + newfile.getPath());
InputStream in = new
BufferedInputStream(uploadRequest.getFileAsStream("fileName"));
FileInputStream fis = new FileInputStream(file); FileOutputStream fos
= new FileOutputStream(newfile);

delete a folder in java

The folder I need to delete is one that is created from my program. The directory is not the same on every pc so the folder code I am using is
userprofile+"\\Downloads\\Software_Tokens"
There will be files in, so I guess i need to recursively delete it. I looked at some samples for that here but it never accepts my path. The path works fine in the code as an environmental variable, because i added code for it
static String userprofile = System.getenv("USERPROFILE");
so can someone just show me the code with my path plugged please?
If your directory is not empty, you may use the Apache Commons IO API's method deleteDirectory(File file) :
String toDelete = userprofile + File.separator + "Downloads" +
File.separator + "Software_Tokens";
FileUtils.deleteDirectory(new File(toDelete));
Be careful with the / or \ that are system dependent and use File.separator instead.
If you don't want to use apache library ! You can do it recursively.
String directory = userprofile + File.separator + "Downloads" + File.separator + "Software_Tokens";
if (!directory.exists()) {
System.out.println("Directory does not exist.");
System.exit(0);
} else {
try {
delete(directory);
} catch (IOException e) {
e.printStackTrace();
System.exit(0);
}
}
System.out.println("Done");
}
public static void delete(File file)
throws IOException {
if (file.isDirectory()) {
//directory is empty, then delete it
if (file.list().length == 0) {
file.delete();
System.out.println("Directory is deleted : " + file.getAbsolutePath());
} else {
//list all the directory contents
String files[] = file.list();
for (String temp: files) {
//construct the file structure
File fileDelete = new File(file, temp);
//recursive delete
delete(fileDelete);
}
//check the directory again, if empty then delete it
if (file.list().length == 0) {
file.delete();
System.out.println("Directory is deleted : " + file.getAbsolutePath());
}
}
} else {
//if file, then delete it
file.delete();
System.out.println("File is deleted : " + file.getAbsolutePath());
}

InputStream is null

In a program I'm working on I have
String cwd;
String file_separator;
public ConfigLoader()
{
cwd = get_cwd();
file_separator = get_file_separator();
try
{
Properties c = new Properties();
InputStream in = this.getClass().getClassLoader().getResourceAsStream(cwd +
file_separator + "data" + file_separator + "configuration.properties");
c.load(in);
}
except (Exception e) { e.printStackTrace(); }
}
public String get_file_separator()
{
File f = new File("");
return f.separator;
}
public String get_cwd()
{
File cwd = new File("");
return cwd.getAbsolutePath();
}
For some reason, though, c.load(in); causes a NullPointerException. The exception comes from in == NULL being true. I can't figure out why because
System.out.println(cwd + file_separator + "data" + file_separator +
"configuration.properties");
prints
/users/labnet/st10/jjb127/workspace/Brewer-Client/data/configuration.properties
which is the location of the file I'm wanting to use.
Thoughts?
getResourceAsStream is meant to search for files on the classpath and not for accessing the local file system. You will have to use FileInputStream for this case.
InputStream in = new FileInputStream(cwd +
file_separator + "data" + file_separator + "configuration.properties");

Categories

Resources