A story about running a program that copies files in Java from a bat file to make the work done every day a little more efficient

Preface

I will submit an in-house diary every day. To be honest, it's hard to copy files every day and put in today's date. I'm not good at clicking.

That's why I automated it as much as possible.

Specifically, a copy with the date in the file name will be generated with a single double click. I haven't messed with the contents of the xls file. There seems to be a library that can do that, but this time it's off.

I used Java and batch files.

I was able to do everything I wanted to do and learned.

Explained below.

Java

For the time being, from the program itself.

program

copyReport.java


package copyReport;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

 public class CopyReport {
	public static void main(String[] args) {
		//Ask them to put a folder on their desktop
		String desktopPath = "C:\\Users\\"+System.getProperty("user.name")+"\\Desktop";
		String folderPath = desktopPath+"\\copyreport";

		//Get the file names in the program folder as an array
		File[] files = new File(folderPath).listFiles();

		//Get the copy source file name. I made it possible to change it to my own name.
		String baseFileName = "";
		for(File f:files) {
			if(f.getName().matches(".*Daily report_.*\\.(xls|xlsx|ods)")) {
				baseFileName = f.getName();
			}
		}

		//Check for the existence of the copy source file
		if(baseFileName.isEmpty()) {
			System.out.println("The copy source file was not found under copyreport.");
			return;
		}
		File baseFile = new File(folderPath,baseFileName);
		if(!baseFile.exists()) {
			System.out.println("The copy source file was not found.");
			return;
		}

		//Generate today's filename from date
		String today = LocalDate.now().format(DateTimeFormatter.ofPattern("YYYYMMdd"));
		String outFileName = today + baseFileName.substring(baseFileName.lastIndexOf("Daily report_"));
		System.out.println(outFileName + "Copy as.");

		//Check if it already exists
		File outFile = new File(desktopPath,outFileName);
		if(outFile.exists()) {
			System.out.println("The destination file already exists.");
			return;
		}

		//Output message
		System.out.println("Copy the file.");
		System.out.println("Copy source folder name;"+folderPath);
		System.out.println("Copy source file name:"+baseFile.getName());
		System.out.println();
		System.out.println("Copy destination folder name;"+desktopPath);
		System.out.println("Copy destination file name:"+outFile.getName());

		try {
			//Create a stream from the copy source / destination File instance
			FileInputStream fis = new FileInputStream(baseFile);
			FileOutputStream fos = new FileOutputStream(outFile);

			//Manage buffers and read bytes
			byte[] buf = new byte[256];
			int len=0;
			//Read and write buf each stream until the end of the file
			while((len = fis.read(buf)) != -1) {
				fos.write(buf,0,len);
			}

			//Write out the part that is not written
			fos.flush();

			//Finish accessing the file
			fos.close();
			fis.close();

			//message
			System.out.println("The file was copied successfully.");

		} catch (FileNotFoundException e) {
			System.out.println("Failed to copy the file.");
			e.printStackTrace();
		} catch (IOException e) {
			System.out.println("Failed to copy the file.");
			e.printStackTrace();
		}

	}

}

Program description

Since it is not a tool to be widely published, it is designed to "put a folder directly on the desktop and run it".

Desktop location

The location of the Windows 10 desktop you are using is C: \ user \ (USER name) \ Desktop, which varies from person to person, so get it from System.getproperty (username) and enter it.

File array

Since it is a folder for storing the program, copy source file, and execution bat file, it has a two-stage structure of getting the entire name → getting the name of the copy source file.

match condition

(Arbitrary date item) Daily report_ (Arbitrary name). (Xls or xlsx or ods) Regular expression. The file that matches this is acquired as the copy source file name. By doing this, if your name is included in the original file name, it will be copied as it is.

Check for copy source

I don't think it's excessive, but it's more troublesome when there is a gap.

Generate file name from date

Get today's date as an 8-digit number string. Create a copy destination file name by putting it in the first half of the copy source file name.

Copy destination check

It would be a problem if the daily report that I wrote the content was overwritten (I think I didn't overwrite it in the first place), so check it for the time being.

Copy file

This time I decided to use FileInputStream and FileOutoutStream. It seems that the buf, which is the contents read from FileInputStream in len bytes at a time, is sent to FileOutputStream. When I looked it up, it was written in the same way in every document, but because of that, there were few samples and it was difficult to understand the mechanism.

finally processing

I manually flushed the part that could not be flushed or ended the access. It seems that access termination processing will be done for Java 8 or later.

So that's it for java programming. After that, you can export from Eclipse or double-click the jar to execute it.

Export in eclipse

File-> Export-> Executable jar file, do as it flows. How much should the jar file name, project name, main class name, etc. be aligned? Complete if a jar file is generated around the desktop.

Build Java runtime environment

The one called JRE. Was it a Java Runtime Environment? Required to execute java (java command, javac command) from the command prompt.

If you have Eclipse, it's quick to talk, bring the path from screen → settings → Java → execution environment and put it in the environment variable of the PC. It seems that you can specify java.exe or javac.exe directly, but this time specify the folder where they are directly under. Once I put it in, I left it in, so I completely forgot to put it in and was impatient.

Confirmation of execution

At the command prompt, move "java -jar copyReport.jar" from the folder containing the .jar file and check the operation. The file name is the one when exported from Eclipse.

Create a bat file

Create a .bat file with an appropriate name and edit it with Notepad. Contents like this

copy.bat


@echo off
cd ./copyreport
java -jar copyReport.jar
timeout 5 

Description

The first line

Subsequent command input contents do not have to be displayed (echo off). The command does not have to be displayed (@).

2nd line

A command to move the current position of the console to the copyreport folder directly under the folder that started it. Even if you make a mistake, it will not fall, so you can execute it with confidence. There is a demerit that if the folder named copyreport in the copyreport folder fails, the future will not work.

3rd line

Execute the specified java file as a jar in java

4th line

Close this screen after 5 seconds. If you get a message but want to delete it, add "> nul" at the end. The meaning of this is "Please output the message to nul".

What I learned

I wrote it after reviewing the file operation, but it took almost a whole day. FileInputStream # read is complicated, and it seems that the contents of buf and len are confused depending on the method to overload, so honestly I was very troubled. It doesn't change the PC around the execution environment, so it's easy to forget about it, so be careful.

Recommended Posts

A story about running a program that copies files in Java from a bat file to make the work done every day a little more efficient
[Small story] I tried to make the java ArrayList a little more convenient
The story of forgetting to close a file in Java and failing
Sample program that returns the hash value of a file in Java
I tried to make a program that searches for the target class from the process that is overloaded with Java
A story about the JDK in the Java 11 era
A story about trying to operate JAVA File
A bat file that uses Java in windows
[Ruby] I want to make a program that displays today's day of the week!
How to deal with the type that I thought about writing a Java program for 2 years
The story that Tomcat suffered from a timeout error in Eclipse
A story about changing skills from COBOL cultivated for 5 years in the late 20s to a Web language
A story about a Spring Boot project written in Java that supports Kotlin
A story about converting character codes from UTF-8 to Shift-jis in Ruby
How to get the absolute path of a directory running in Java
What to do about "A server is already running ..." that happened without turning off the rails server in the terminal