<Java> Quiz to batch convert file names separated by a specific character string with a part of the file name

background

--I saw the following article -\ Quiz to convert file names separated by a specific character string at once with a part of the file name ――I felt like I was told to do it in Java, so I will do it.

environment

--I'm doing it on a Mac

$ java -version
openjdk version "14.0.1" 2020-04-14
OpenJDK Runtime Environment AdoptOpenJDK (build 14.0.1+7)
Eclipse OpenJ9 VM AdoptOpenJDK (build openj9-0.20.0, JRE 14 Mac OS X amd64-64-Bit Compressed References 20200416_40 (JIT enabled, AOT enabled)
OpenJ9   - 05fa2d361
OMR      - d4365f371
JCL      - 5757187cae based on jdk-14.0.1+7)

Advance preparation

--Similarly, the original article is done with one liner from the place where the file of ʻabc_test_ok_1_this.csv`` ・ ・ ・ ʻabc_test_ok_100_this.csv`` is prepared, so from there

echo 'IntStream.range(1,101).forEach(i -> {try {Files.createFile(Paths.get("abc_test_ok_"+String.valueOf(i) + "_this.csv"),java.nio.file.attribute.PosixFilePermissions.asFileAttribute(java.nio.file.attribute.PosixFilePermissions.fromString("r--r--r--")));} catch (Exception e) {throw new RuntimeException(e);}})' | jshell -

――It is easy to think that Java is not suitable for one-liner because it requires compilation, but in recent Java, you can use a REPL tool called JShell. --While writing with echo, I'm passing it to the jshell command via a pipe. The last-is to prevent unnecessary display. --The import statement can be omitted depending on the item. ――Since the way to write permissions is Unix-based, I don't think it will work on Windows. ――I thought I would lose if I wrote the loop in a For statement, so I used forEach from Stream without any particular meaning. --If you write it with line breaks, it will be as follows. Exception handling is a hassle.

        IntStream.range(1,101).forEach(i -> {
            try {
                Files.createFile(Paths.get("abc_test_ok_"+String.valueOf(i) + "_this.csv"),
                    PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("r--r--r--")));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });

Rename the file


echo 'Path path1 = Paths.get(".");try{Files.list(path1).forEach(from -> {String intStr = from.toString().replaceAll("[^0-9]", "");try {Files.move(from, Paths.get(".",intStr + ".csv"));} catch (IOException e) {e.printStackTrace();}});} catch(IOException e) {e.printStackTrace();}' | jshell -

--Since only the numbers are taken with regular expressions and renamed to the file name, it may not work if there are extra files in the folder. ――After taking the path of the current directory, you can quickly take the one directly under the list and turn it with forEach, and rename the file with move. --If you write it with line breaks, it will be as follows. After all exception handling seems to be troublesome. (It is meaningless that the post-processing of exception handling is different from the above) -(7/15 postscript) Refactored to use lambda expression.

        Path path1 = Paths.get(".");
        try{
		    Files.list(path1).forEach(from -> {
                String intStr = from.toString().replaceAll("[^0-9]", "");
                try {
                    Files.move(from, Paths.get(".",intStr + ".csv"));
				} catch (IOException e) {
                    e.printStackTrace();
                }
            });
        } catch(IOException e) {e.printStackTrace();}
	}

in conclusion

――I touched JShell for the first time in a long time. It's good to move quickly. ――As with the previous person, I don't usually do much file processing, so I did it while investigating, so please point out if there is a better way.

Recommended Posts

<Java> Quiz to batch convert file names separated by a specific character string with a part of the file name
[Java] Cut out a part of the character string with Matcher and regular expression
[Java] How to use substring to cut out a part of a character string
[Java] How to get to the front of a specific string using the String class
I want to get a list of only unique character strings by excluding fixed character strings from the file name
[Java] How to cut out a character string character by character
[Java] How to erase a specific character from a character string
[Java] How to convert a character string from String type to byte type
Read the file under the classpath as a character string with spring
Connecting to a database with Java (Part 1) Maybe the basic method
Overwrite upload of file with the same name with BOX SDK (java)
How to check for the contents of a java fixed-length string
About the method to convert a character string to an integer / decimal number (cast data) in Java
The story of forgetting to close a file in Java and failing
Extract a part of a string with Ruby
How to find out the Java version of a compiled class file
[Java] How to easily get the longest character string of ArrayList using stream
I was swallowed by the darkness of the romaji, trying to convert my name to romaji
Read a string in a PDF file with Java
[Android] How to convert a character string to resourceId
[Java] The confusing part of String and StringBuilder
Set the time of LocalDateTime to a specific time
Convert a string to a character-by-character array with swift
[Java] When putting a character string in the case of a switch statement, it is necessary to make it a constant expression
I want to find the MD5 checksum of a file in Java and get the result as a string in hexadecimal notation.
[Java] Integer information of characters in a text file acquired by the read () method
How to save a file with the specified extension under the directory specified in Java to the list
# 1_JAVA I want to get the index number by specifying one character in the character string.
<java> Read Zip file and convert directly to string
Mastering Kotlin ~ Convert Java File to Kotlin File Road to Graduation ~ Part 3
Submit a job to AWS Batch with Java (Eclipse)
Mastering Kotlin ~ Convert Java File to Kotlin File Road to Graduation ~ Part 2
[Java] How to extract the file name from the path
I want to monitor a specific file with WatchService
Mastering Kotlin ~ Convert Java File to Kotlin File Road to Graduation ~ Part 1
How to convert a file to a byte array in Java
[Kotlin] Convert ZonedDateTime to String by specifying the format
Replace only part of the URL host with java
Convert a Java byte array to a string in hexadecimal notation
Initialization with an empty string to an instance of Java String type
[Java] How to use substring to cut out a character string
I tried to convert a string to a LocalDate type in Java
About the behavior when doing a file map with java
Be sure to compare the result of Java compareTo with 0
I tried OCR processing a PDF file with Java part2
[Introduction to Java] Handling of character strings (String class, StringBuilder class)
How to change the file name with Xcode (Refactor Rename)
Convert Excel to Blob with java, save it, read it from DB and output it as a file!
Code to specify the image name as a character string and paste it into ImageView (android)
[Java beginner] Conversion from character string to numerical value-What is the parseInt method of the Integer class? ~
Try to imitate the idea of a two-dimensional array with a one-dimensional array
When the character string passed to C ++ by JNA is garbled
I can't create a Java class with a specific name in IntelliJ
The story of not knowing the behavior of String by passing Java by reference
Fix the file name of war to the one set in Maven
[Rails] How to omit the display of the character string of the link_to method
Replace with a value according to the match with a Java regular expression
A story about hitting the League Of Legends API with JAVA
Get the public URL of a private Flickr file in Java
Add a time stamp to the JAR file name in Gradle
[Java] Appropriate introduction by the people of Tempa Java Part 0 (Code rules)