Java Files.readAllBytes example

摘要: In Java, we can use Files.readAllBytes to read a file.

In Java, we can use Files.readAllBytes to read a file.

	byte[] content = Files.readAllBytes(Paths.get("app.log"));
    System.out.println(new String(content));

1. Text File

A Java example to write and read a normal text file.

FileExample1.java
package com.mkyong.calculator;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
public class FileExample1 {
    public static void main(String[] args) {
        Charset utf8 = StandardCharsets.UTF_8;
        List<String> list = Arrays.asList("Line 1", "Line 2");
		// Write
        try {
            Files.write(Paths.get("app.log"), list, utf8, 
				StandardOpenOption.CREATE, StandardOpenOption.APPEND);
        } catch (IOException x) {
            System.err.format("IOException: %s%n", x);
        // Read
        try {
            byte[] content = Files.readAllBytes(Paths.get("app.log"));
            System.out.println(new String(content));
            // for binary
            //System.out.println(Arrays.toString(content));
        } catch (IOException e) {
            e.printStackTrace();

Output

app.log
Line 1
Line 2

2. Binary File

For binary format, we need to use Arrays.toString to convert it to a String.

FileExample2.java
package com.mkyong;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Arrays;
public class FileExample2 {
    public static void main(String[] args) {
        byte[] bytes = {1, 2, 3, 4, 5};
		// Write into binary format
        try {
            Files.write(Paths.get("app.bin"), bytes, 
				StandardOpenOption.CREATE, StandardOpenOption.APPEND);
        } catch (IOException x) {
            System.err.format("IOException: %s%n", x);
        // Read
        try {
            byte[] content = Files.readAllBytes(Paths.get("app.bin"));
            // for binary
            System.out.println(Arrays.toString(content));
        } catch (IOException e) {
            e.printStackTrace();

Output

app.bin
[1, 2, 3, 4, 5]

上一篇: Java How to append text to a file
下一篇: Maven source value 1.5 is obsolete and will be removed in a future release
 评论 ( What Do You Think )
名称
邮箱
网址
评论
验证
   
 

 


  • 微信公众号

  • 我的微信

站点声明:

1、一号门博客CMS,由Python, MySQL, Nginx, Wsgi 强力驱动

2、部分文章或者资源来源于互联网, 有时候很难判断是否侵权, 若有侵权, 请联系邮箱:summer@yihaomen.com, 同时欢迎大家注册用户,主动发布无版权争议的 文章/资源.

3、鄂ICP备14001754号-3, 鄂公网安备 42280202422812号