First touch of the Files class (or Java 8)

Files class that I touched for the first time

It may not even be the first step, but I will do it little by little. 2019/04/19 Updated a little.

Read file contents

input_01.csv


"ID","class","name"
"0001","Saber","Altria"
"0002","caster","media"
"0003","Berserker","Hercules"

input_02.csv


"ID","Ship type","name"
"0001","Battleship","Nagato"
"0002","a light cruiser","Abukuma"
"0003","Destroyer","heat haze"

Source

FileInOutFirst.java


package com.otamesi;

import java.io.BufferedReader;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

public class FileInOutFirst{

	/**
	 *The first Files class.
	 *
	 */
	public static void main(String args[]) throws Exception{

		FileInOutFirst fileInOutFirst = new FileInOutFirst();
		fileInOutFirst.inOut01();
		fileInOutFirst.inOut02();
		fileInOutFirst.inOut03();
		fileInOutFirst.inOut04();
		fileInOutFirst.inOut05();
	}

	/**
	 *Part 1.<br>
	 *For the time being, try to output to standard output.
	 *
	 */
	private void inOut01() throws Exception {
		//Read SJIS file
		List<String> input = Files.readAllLines(Paths.get("D:/", "input_01.csv"), Charset.forName("SJIS"));
		System.out.println("Part 1");
		input.forEach(line -> System.out.println(line));
	}

	/**
	 *Part 2.<br>
	 *For the time being, try to output to standard output(UTF-8)。
	 *
	 */
	private void inOut02() throws Exception {
		//UTF-Read 8 files
		List<String> input = Files.readAllLines(Paths.get("D:/", "input_02.csv"), StandardCharsets.UTF_8);

		System.out.println("Part 2");
		input.forEach(line -> System.out.println(line));
	}

	/**
	 *Part 3.<br>
	 *For the time being, try to output to standard output(UTF-8)。
	 *
	 */
	private void inOut03() throws Exception {
		//UTF-Read 8 files
		List<String> input = Files.readAllLines(Paths.get("D:/", "input_03.csv"), StandardCharsets.UTF_8);

		System.out.println("Part 3");
		input.forEach(System.out::println);
	}

	/**
	 *Part 4.<br>
	 *For the time being, try to output to standard output(UTF-8)。
	 *
	 */
	private void inOut04() throws Exception {
		//UTF-Read 8 files
		List<String> input = Files.readAllLines(Paths.get("D:/", "input_03.csv"), StandardCharsets.UTF_8);
		List<String> input2 = new ArrayList<String>();
		System.out.println("Part 4");
		input.forEach(input2::add);
		input2.forEach(System.out::println);
	}

	/**
	 *Part 5.<br>
	 *Use newBufferedReader(For large files)
	 *
	 */
	private void inOut05() throws Exception {
		System.out.println("Part 5");
		Path file = Paths.get("D:/", "input_03.csv");
		try (BufferedReader br = Files.newBufferedReader(file, StandardCharsets.UTF_8)) {
			String text;
			while ((text = br.readLine()) != null) {
				System.out.println(text);
			}
		}
	}
}

Output result

Part 1 "ID", "class", "name" "0001", "Saber", "Altria" "0002", "Caster", "Media" "0003", "Berserker", "Heracles" Part 2 "ID", "ship type", "name" "0001", "Battleship", "Nagato" "0002", "Light Cruiser", "Abukuma" "0003", "Destroyer", "Kagero"

Try it for the time being

This is the first forEach method, but you can write a loop very neatly! Also, constants are prepared for encoding, which is convenient (unfortunately there seems to be no SJIS).

If you specify a character code different from the character code of the file as a parameter, The following exception occurs. You may have a chance to encounter it, so let's remember ...

Exception in thread "main" java.nio.charset.MalformedInputException: Input length = 1
	at java.nio.charset.CoderResult.throwException(CoderResult.java:281)
	at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:339)
	at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:178)
	at java.io.InputStreamReader.read(InputStreamReader.java:184)
	at java.io.BufferedReader.fill(BufferedReader.java:161)
	at java.io.BufferedReader.readLine(BufferedReader.java:324)
	at java.io.BufferedReader.readLine(BufferedReader.java:389)
	at java.nio.file.Files.readAllLines(Files.java:3205)

Recommended Posts

First touch of the Files class (or Java 8)
Read the first 4 bytes of the Java class file and output CAFEBABE
Summarize the additional elements of the Optional class in Java 9
Java: The problem of which is faster, stream or loop
[Java] Delete the elements of List
[Java version] The story of serialization
How to disassemble Java class files
How to decompile java class files
Various methods of the String class
The origin of Java lambda expressions
Examine the list of timezone IDs available in the Java ZoneId class
I want to judge the necessity of testing by comparing the difference of class files when refactoring Java
Get the result of POST in Java
[Java] How to use the File class
Check the contents of the Java certificate store
Automatically adjust the height of Xib files
Examine the memory usage of Java elements
Introduction to java for the first time # 2
[Java Servlet] The road of Senri is also the fifth step from the first step
[Java] Get the day of the specific day of the week
[Java Servlet] The road of Senri is also one step to the first
Let's express the result of analyzing Java bytecode with a class diagram
[Java] How to use the HashMap class
Memo: [Java] Check the contents of the directory
[Java Servlet] The road of Senri is also the third step from the first step
[Java] Inheritance and structure of HttpServlet class
Compare the elements of an array (Java)
[day: 5] I summarized the basics of Java
What are the updated features of java 13
Easily measure the size of Java Objects
How to find out the Java version of a compiled class file
Looking back on the basics of Java
[Processing × Java] How to use the class
[Java] How to get to the front of a specific string using the String class
Output of the book "Introduction to Java"
Learning for the first time java [Introduction]
Memo: [Java] Identify files with an update date of 1 day or less
[Socket communication (Java)] Impressions of implementing Socket communication in practice for the first time
From Java9, the constructor of the class corresponding to primitive types is deprecated.
The story of writing Java in Emacs
[Java] How to use the Calendar class
[Java] Check the number of occurrences of characters
[Java Servlet] The road of Senri is also the fourth step from the first step
[Java] [Spring] Test the behavior of the logger
[Java] Get the date with the LocalDateTime class
Display Japanese calendar and days of the week using java8 standard class
[Promotion of Ruby comprehension (1)] When switching from Java to Ruby, first understand the difference.
The first year of working people summarized how to take the Java Bronze exam
Increment with the third argument of iterate method of Stream class added from Java9
Code that deletes all files of the specified prefix in AWS S3 (Java)
[Code] Forcibly breaks through the C problem "* 3 or / 2" of [AtCoder Problem-ABC100] with Java [Code]
[Java] Calculate the day of the week from the date (Calendar class is not used)
[Ruby] Summary of class definitions. Master the basics.
[Java] Handling of JavaBeans in the method chain
The story of making ordinary Othello in Java
[Android] [Java] Manage the state of CheckBox of ListView
About the idea of anonymous classes in Java
[Delete the first letter of the character string] Ruby
The order of Java method modifiers is fixed
Measure the size of a folder in Java
[Java] Get the length of the surrogate pair string