FastFoodCoding

Login


Connect with one of the following accounts





Login

Please wait while we redirect...

Views: 432   



Reading Files

Read all lines in a file into a List

You can read the lines as List of Strings (Each line as a String) with following code.

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;

class FilesHandling {
    public static void main(String[] args) {
        try {
            List<String> lines = Files.readAllLines(Paths.get("/path/to/file.txt"));
            int lineNum = 1;
            for (String line : lines) {
                System.out.println("Line No:" + lineNum + " Content:" + line);
                lineNum++;
            }
        } catch (IOException e) {
            // looks like the file not found with given path
            e.printStackTrace();
        }
    }
}

File content into String

You can read the complete file content into a String with the following code

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

class FilesHandling {
    public static void main(String[] args) {
        try {
            String fileContent = new String(Files.readAllBytes(Paths.get("/path/to/file.txt")));
            System.out.println("File Content is:" + fileContent);
        } catch (IOException e) {
            // looks like the file not found with given path
            e.printStackTrace();
        }
    }
}

Writing Files

You can write content into a File using following code.

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

class FilesHandling {
    public static void main(String[] args) {
        try {
            String contentTobeWritten = "This is the new content you will see in file";
            Files.write(Paths.get("/path/to/file"), contentTobeWritten.getBytes(), StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
        } catch (IOException e) {
            // looks like the file not found with given path
            e.printStackTrace();
        }
    }
}



On By


Top Tutorials

Top Questions

Top Articles

Top Blogs

Top News