Folder monitor Java code prints report twice - java

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.

Related

Delete an Excel file after processing in Java

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().

Writing to Google Persistent DIsk

I've written some java code that creates a CSV file at the mount point of a disk I have attached to a Google Compute instance. I run the script in the form of a SQL stored procedure from the instance that the disk is attached to. The issue is that at the mount point, a "lost+found" folder is created where I would expect to find my CSV file. What am I doing wrong? Thank you for your time! The code is similar to as follows:
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.FileOutputStream;
public class file_write {
public static void main(String[] args) throws IOException{
String filePath = "/mnt/point/file.csv";
// Creates file in mount point
File myFile = new File(filePath);
myFile.getParentFile().mkdirs();
myFile.createNewFile();
FileWriter stringWriter = new FileWriter(myFile);
for(int i = 0; i < 100000; i++) {
stringWriter.write(i + ", ");
stringWriter.write("something");
stringWriter.write(System.lineSeparator());
}
stringWriter.close();
}
}

Java Creating copy of file before uploading to AWS cloud

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());
}
}

Can Jetty capture System.out and System.err to a log file?

I am working with Jetty embedded server, building a REST api out of a legacy jar, which has a lot of critically useful calls to println (I run its classes and it prints stuff in console). I am trying now to have these printlns in a file, along with the requests status, but the NCSARequestLog only logs in the file date and code of the responses. Is there a way to log everything in a file then? I'm pretty sure it is possible because before we were wrapping the legacy jar in a war file deployed into Glassfish, and all prints used to show up in the server log.
Thanks
In the jetty-util-<ver>.jar there is a class called RolloverFileOutputStream which can be instantiated and then set to take over the roll of System.out and System.err
An example of this:
package demo;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.util.TimeZone;
import org.eclipse.jetty.util.RolloverFileOutputStream;
public class ConsoleCaptureDemo
{
public static void main(String[] args) throws IOException
{
File loggingDir = new File("logs");
if (!loggingDir.exists())
{
if (!loggingDir.mkdirs())
{
throw new RuntimeException("Unable to create directory: " + loggingDir);
}
}
String loggingFile = new File(loggingDir, "yyyy_mm_dd.jetty.log").getAbsolutePath();
boolean append = false;
int retainDays = 90;
TimeZone zone = TimeZone.getTimeZone("GMT");
RolloverFileOutputStream logStream = new RolloverFileOutputStream(loggingFile,
append, retainDays, zone);
System.out.println("Look at " + logStream.getFilename());
PrintStream logWriter = new PrintStream(logStream);
System.setOut(logWriter);
System.setErr(logWriter);
System.out.println("From System.out - hi there");
System.err.println("From System.err - hello again");
}
}

PrintWriter not writing to the file but I closed the writer? (java)

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.

Categories