Try-with-resources block to simplify error-handling and make the code more concise - Java Language Basics

Java examples for Language Basics:try with Resources

Description

Try-with-resources block to simplify error-handling and make the code more concise

Demo Code

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;

public class Main {

    public static void main(String[] args) {
        try (BufferedReader inputReader = Files.newBufferedReader(
                        Paths.get(new URI("file:///C:/home/docs/users.txt")),
                        Charset.defaultCharset());
                BufferedWriter outputWriter = Files.newBufferedWriter(
                        Paths.get(new URI("file:///C:/home/docs/users.bak")),
                        Charset.defaultCharset())) {
            String inputLine;/*from ww  w  . j a  va  2  s  .c o  m*/
            while ((inputLine = inputReader.readLine()) != null) {
                outputWriter.write(inputLine);
                outputWriter.newLine();
            }
            System.out.println("Copy complete!");
        } catch (URISyntaxException | IOException ex) {
            ex.printStackTrace();
        }



    }
}

Related Tutorials