I want to take an input Java file from an HTMl form process it using servlets, and delete it after use.
However I am not able to find any viable solutions for the same. What are the options I can go about to delete the file from the project folder after I am done with it.
Below is my code:
public class TryWithResources extends fileUpload{
public static void main(String args[]){
try {
FileInputStream fis= new FileInputStream("C:\\Users\\khuha\\eclipse-
workspace\\firstDemo\\fileData");
XSSFWorkbook wb=new XSSFWorkbook(fis);
System.out.println("Enter the sheet you want to search in: ");
Scanner sc= new Scanner(System.in);
int n= sc.nextInt();
XSSFSheet sheet=wb.getSheetAt(n-1);
Iterator<Row> itr=sheet.iterator();
while(itr.hasNext()) {
Row row=itr.next();
Iterator<Cell> cellIterator=row.cellIterator();
while(cellIterator.hasNext()) {
Cell cell=cellIterator.next();
Cell name_cell=row.getCell(0);
String name=name_cell.getStringCellValue();
if (cell.getRowIndex()!=0 && cell.getStringCellValue().equals("")&& cell.getColumnIndex()!=0){
int idate=cell.getColumnIndex();
Row first_row=sheet.getRow(0);
Cell date_cell=first_row.getCell(idate);
Date sdate=date_cell.getDateCellValue();
SimpleDateFormat formatter = new SimpleDateFormat("E MMM dd HH:mm:ss z yyyy");
String strDate = formatter.format(sdate);
if (AttendanceUtils.DayCheck(sdate)){
Locale locale=Locale.getDefault();
System.out.println("No entry found for "+name+" on "+ strDate.substring(8,10)+"-"+AttendanceUtils.getmonth( sdate)+"-"+strDate.substring(24,28) +" "+ AttendanceUtils.getDayStringOld(sdate,locale));
}
}
}
}
System.out.println("");
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
The code for the servlet which helps upload this file is
package attendanceApp;
import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class fileUpload extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
try {
ServletFileUpload sf=new ServletFileUpload(new DiskFileItemFactory());
List<FileItem> multifiles = sf.parseRequest(request);
//String file="";
for(FileItem item : multifiles)
{
//file =item.getName();
item.write(new File("C:\\Users\\khuha\\eclipse-workspace\\firstDemo\\fileData"));
}
}
catch(Exception e) {
System.out.println(e);
}
}
public String fileName(String files){
return files;
//ignore this function, created to explore another solution
}
}
I am exploring two options here
one to go about using TryWithResources, but I am not sure how it will implement delete operation.
to write every file uploaded as fileData, perform functions on it and delte it then and there.
In both the cases I will need to delete the file after use, also to optimise memory it is not really feasible to store every file uploaded.
So, how can I perform the delete functions in the above codes?
Thanks.
Ensure your output file stream is properly closed after writing, and your input file stream is properly closed after reading. Then the file should be good to delete.
If File.delete() returns false, run File.deleteOnExit().
If i use the code
File file = File.createTempFile(fileName, null);
then i won't have to create a location for file in the disk and hence the file can be deleted on exit from application.
This can be achieved using the function:
file.deleteOnExit().
Related
I have an image in a directory.
I want to make a copy of that image with a different name without doing harm to the original image in the same directory.
So there will be two same images in one folder with a different name.
I want a basic code like I tried -
File source = new File("resources/"+getImage(0));
File dest = new File("resources/");
source.renameTo("resources/"+getImage(0)+);
try {
FileUtils.copyDirectory(source, dest);
} catch (IOException e) {
e.printStackTrace();
}
When I upload the same image to the Amazon server multiple times in automation and then it starts giving issue to upload.
So we want to upload a mirror copy of image everytime.
In eclipse generally have resources folder. I want to make copy of a original image every-time before we upload and delete it after upload.
Kindly suggest some approach
You can just copy the file and use StandardCopyOption.COPY_ATTRIBUTES
public static final StandardCopyOption COPY_ATTRIBUTES
Copy attributes to the new file.
Files.copy(Paths.get(//path//to//file//and//filename),
Paths.get(//path//to//file//and//newfilename), StandardCopyOption.COPY_ATTRIBUTES);
Not a perfect solution, but Instead of handling pop-up box we can directly force file path into the form: [I have used date-stamp for creating new filenames but some different logic could also be used viz- Random String appender etc.]
import org.junit.jupiter.api.Test;
import java.io.*;
import java.nio.file.Files;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class Upload {
private static final String SRC_RESOURCES_FILE_PATH = System.getProperty("user.dir")+"/src/resources/";
File s1 = new File(SRC_RESOURCES_FILE_PATH+"Img1.png");
File s2 = new File(SRC_RESOURCES_FILE_PATH+"Img"+getDateStamp()+".png");
#Test
public void uploadFunction() throws IOException {
copyFileUsingJava7Files(s1,s2);
}
private String getDateStamp(){
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date();
return dateFormat.format(date).toString();
}
private static void copyFileUsingJava7Files(File source, File dest)
throws IOException {
Files.copy(source.toPath(), dest.toPath());
}
}
I'm trying to create a new excel file with just "hello" in it.
Here's my code:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
/**
*
* #author kamal
*/
public class JavaApplication4 {
private static String dir = "";
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
try {
// TODO code application logic here
JFileChooser jc = new JFileChooser();
jc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int output = jc.showOpenDialog(null);
if(output == JFileChooser.APPROVE_OPTION){
File f = jc.getSelectedFile();
String directory = f.getAbsolutePath();
setDir(directory);
}
FileOutputStream out = new FileOutputStream(new File(getDir()+"\\Book2.xlsx"));
FileInputStream in = new FileInputStream(new File(getDir()+"\\Book2.xlsx"));
org.apache.poi.ss.usermodel.Workbook workbook = new XSSFWorkbook(in);
org.apache.poi.ss.usermodel.Sheet sheet = workbook.getSheetAt(0);
sheet.createRow(0).createCell(0).setCellValue("hello");
workbook.write(out);
workbook.close();
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
Logger.getLogger(JavaApplication4.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* #return the dir
*/
public static String getDir() {
return dir;
}
/**
* #param dir the dir to set
*/
public static void setDir(String directory) {
dir = directory;
}
}
..And when I run it I get the following error:
Exception in thread "main" org.apache.poi.openxml4j.exceptions.NotOfficeXmlFileException: No valid entries or contents found, this is not a valid OOXML (Office Open XML) file
at org.apache.poi.openxml4j.opc.ZipPackage.getPartsImpl(ZipPackage.java:286)
at org.apache.poi.openxml4j.opc.OPCPackage.getParts(OPCPackage.java:758)
at org.apache.poi.openxml4j.opc.OPCPackage.open(OPCPackage.java:327)
at org.apache.poi.util.PackageHelper.open(PackageHelper.java:37)
at org.apache.poi.xssf.usermodel.XSSFWorkbook.<init>(XSSFWorkbook.java:291)
at javaapplication4.JavaApplication4.main(JavaApplication4.java:46)
C:\Users\kamal\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 7 seconds)
I looked up this code in youtube and it's same but i'm not sure why am i getting the error? Can you help me with this?
I think the most likely explanations are that either the file is corrupt, or it is an older format spreadsheet file that XSSFWorkbook does not understand.
It is unlikely anyone can give you a definite diagnosis without looking at the file itself.
Okay. Today I encountered the same problem . The server was linux and the excel file is copied from windows to linux through winscp. Winscp has options like transferring the file in binary mode , text mode etc. When we copy the excel file through text mode , I got the same error you mentioned. The error got resolved when I copy the excel file using binary mode. To summarize , this issue came because we copied excel file from windows to linux. Just make sure you are copying in binary mode if using winscp. Make sure the file is copied correctly.
I was facing the same problem. I did create the Excel file by doing right click inside the folder and then ->New->Microsoft Excel Worksheet.
As a trial I removed this file and then created the new Excel through Start Menu->Microsoft Office->Excel
It worked for me, Hopefully same will work for you too.
Using some answers from this site I created a small Folder Monitor app in Java. It is supposed to check for changes to a specific folder and output those changes to a text file. Unfortunately it prints the report twice for every change. The problem is I cannot figure out where the first line of the report comes from. Please help me understand what am I doing wrong.
Please find the code below. I removed part of the code as it does not affect the Q&A.
import java.io.File;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.commons.io.monitor.FileAlterationListener;
import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;
public class FolderMonitor {
public FolderMonitor() {}
//path to a folder you are monitoring
public static final String FOLDER = "D:\\WatchedDir";
public static void main(String[] args) throws Exception
{
System.out.println("monitoring started");
// The monitor will perform polling on the folder every 5 seconds
final long pollingInterval = 6 * 1000;
// Let's get a directory as a File object and sort all its files.
File folderToMonitor = new File(FOLDER);
File outputFile = new File("H:\\Dir_changes.txt");
if (!folderToMonitor.exists())
{
// Test to see if monitored folder exists
throw new RuntimeException("Directory not found: " + FOLDER);
}
FileAlterationObserver observer = new FileAlterationObserver(folderToMonitor);
FileAlterationMonitor monitor = new FileAlterationMonitor(pollingInterval);
FileAlterationListener listener = new FileAlterationListenerAdaptor()
{
// Is triggered when a file in the monitored folder is modified from
#Override
public void onFileChange(File file)
{
// "file" is the reference to the newly created file
try {writeToFile(outputFile, convertLongToDate(outputFile.lastModified()), ("File modified: "+ file.getCanonicalPath()));}
catch (IOException e) {e.printStackTrace();}
}
};
observer.addListener(listener);
monitor.addObserver(observer);
monitor.start();
}
private static void writeToFile(File filePath, String timeStamp, String caughtChange) throws IOException
{
FileWriter fileWriter = new FileWriter(filePath,true);
BufferedWriter bufferFileWriter = new BufferedWriter(fileWriter);
fileWriter.append("\r" + timeStamp + " - " + caughtChange + "\r");
bufferFileWriter.close();
}
private static String convertLongToDate(long input)
{
Date date = new Date(input);
Calendar cal = new GregorianCalendar();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MMM/dd hh:mm:ss z");
sdf.setCalendar(cal);
cal.setTime(date);
return sdf.format(date);
}
}
The output looks like this:
1454622374878 File modified: D:\WatchedDir\second\inside3.txt
2016/Feb/04 04:46:25 EST - File modified: D:\WatchedDir\second\inside3.txt
I can not figure out where the highlighted (bold) part comes from and how to get rid of it. Please help!
I ran the same code that you posted and don't see the extra output in the .txt file. can you please try it by directing the output to a new file and see if it makes any difference
For some reason Eclipse was executing code that I have already removed from the class and saved the changes.
After I have restarted Eclipse and executed the code again, everything was running fine (surprise).
I considered deleting this post but I decided to leave it just in case someone will be looking for such a piece of code. I will leave it to the moderators to decide if this question should be deleted.
I'm trying to write some text to an html file as an output using PrintWriter, and the text isn't saving to the file.
import java.util.Random;
import java.util.*;
import java.io.PrintWriter;
import java.io.File;
import java.io.FileNotFoundException;
public class Creator
{
static ArrayList<Character> grid = new ArrayList<Character>();
public static void main(String[]args) throws FileNotFoundException
{
char[] alphabet={'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
for(int row=0;row<625;row++)
{
grid.add(alphabet[RandGen(0,25)]);
//System.out.print(grid.get(out));
}
Creator.Output();
System.out.println("Executed.");
}
public static int RandGen(int min, int max)
{
Random ran = new Random();
int randomNum = ran.nextInt(max) + min;
return randomNum;
}
public static void Output()throws FileNotFoundException
{
//File file=new File("wsm.html");
//File.createNewFile();
PrintWriter writer = new PrintWriter("wordsearchmaker.html");
writer.println("<html>");
writer.println("<table>");
writer.println("tr");
for(int j=0;j<25;j++)
{
//for(int k=0;k<25;k++)
// {
System.out.println("<th>"+grid.get(j));
writer.println("<th>"+grid.get(j));
// }
}
writer.flush();
writer.close();
System.out.println("Outputting...");
}
}
So I've checked that the methods are all running (hence the "outputting..."), and I system.out.printed the content that I'm intending to write to the file, which is outputting exactly what I want it to. It's supposed to output html code into a html file (named wordsearchmaker.html), but nothing is saving to the file. Everywhere I looked online just said to make sure I'm closing the writer, which I did.
Note: I am working in eclipse, which has always been kind of finicky with me, so I may be messing something up there? I don't usually work in eclipse so that's totally possible.
It looks like you've opened the PrintWriter, which enables you to send data to the file. But you haven't actually opened or created a file.
Try first creating a new file and modifying it:
import java.io.File;
File newFile = new File ("LOCATION OF FILE");
Then, set your PrintWriter to use newFile.
I have to move files from one directory to other directory.
Am using property file. So the source and destination path is stored in property file.
Am haivng property reader class also.
In my source directory am having lots of files. One file should move to other directory if its complete the operation.
File size is more than 500MB.
import java.io.File;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import static java.nio.file.StandardCopyOption.*;
public class Main1
{
public static String primarydir="";
public static String secondarydir="";
public static void main(String[] argv)
throws Exception
{
primarydir=PropertyReader.getProperty("primarydir");
System.out.println(primarydir);
secondarydir=PropertyReader.getProperty("secondarydir");
File dir = new File(primarydir);
secondarydir=PropertyReader.getProperty("secondarydir");
String[] children = dir.list();
if (children == null)
{
System.out.println("does not exist or is not a directory");
}
else
{
for (int i = 0; i < children.length; i++)
{
String filename = children[i];
System.out.println(filename);
try
{
File oldFile = new File(primarydir,children[i]);
System.out.println( "Before Moving"+oldFile.getName());
if (oldFile.renameTo(new File(secondarydir+oldFile.getName())))
{
System.out.println("The file was moved successfully to the new folder");
}
else
{
System.out.println("The File was not moved.");
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
System.out.println("ok");
}
}
}
My code is not moving the file into the correct path.
This is my property file
primarydir=C:/Desktop/A
secondarydir=D:/B
enter code here
Files should be in B drive. How to do? Any one can help me..!!
Change this:
oldFile.renameTo(new File(secondarydir+oldFile.getName()))
To this:
oldFile.renameTo(new File(secondarydir, oldFile.getName()))
It's best not to use string concatenation to join path segments, as the proper way to do it may be platform-dependent.
Edit: If you can use JDK 1.7 APIs, you can use Files.move() instead of File.renameTo()
Code - a java method:
/**
* copy by transfer, use this for cross partition copy,
* #param sFile source file,
* #param tFile target file,
* #throws IOException
*/
public static void copyByTransfer(File sFile, File tFile) throws IOException {
FileInputStream fInput = new FileInputStream(sFile);
FileOutputStream fOutput = new FileOutputStream(tFile);
FileChannel fReadChannel = fInput.getChannel();
FileChannel fWriteChannel = fOutput.getChannel();
fReadChannel.transferTo(0, fReadChannel.size(), fWriteChannel);
fReadChannel.close();
fWriteChannel.close();
fInput.close();
fOutput.close();
}
The method use nio, it make use os underling operation to improve performance.
Here is the import code:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
If you are in eclipse, just use ctrl + shift + o.