Reading and writing files in Java (Input/Output) - Tutorial

Java Input Output

This tutorial explains how to read and write files via Java.


Table of Contents

1. Java I/O (Input / Output) for files
1.1. Overview
1.2. Reading a file in Java
1.3. Writing a file in Java
1.4. How to identify the current directory
2. Exercise: Reading and writing files
3. Reading resources out of your project / jar
4. About this website
4.1.
5. Links and Literature

1. Java I/O (Input / Output) for files

1.1. Overview

Java provides a standard way of reading from and writing to files. Traditionally the java.io package was used, but in modern Java applications you use the java.nio.file API.

Java will read all input as a stream of bytes. The InputStream class is the superclass of all classes representing an input stream of bytes.

1.2. Reading a file in Java

To read a text file you can use the Files.readAllBytes method as demonstrated by the following listing.

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

// somewhere in your code
String content = new String(Files.readAllBytes(Paths.get(fileName))); 

To read a text file line by line into a List of type String structure you can use the following example.

List<String> lines = Files.readAllLines(Paths.get(fileName)); 

1.3. Writing a file in Java

To write a file you can use the following method:

Files.write(Paths.get(fileName), content.getBytes(), StandardOpenOption.CREATE); 

1.4. How to identify the current directory

You can access files relative to the current execution directory of your Java program. To print the current directory in which your Java program is running, you can use the following statement.

System.out.println(System.getProperty("user.dir")); 

2. Exercise: Reading and writing files

Create a new Java project called com.vogella.java.files. Create the following FilesUtil.java class.

package com.vogella.java.files;

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

public class FilesUtil {
  public static String readTextFile(String fileName) throws IOException {
    String content = new String(Files.readAllBytes(Paths.get(fileName)));
    return content;
  }

  public static List<String> readTextFileByLines(String fileName) throws IOException {
    List<String> lines = Files.readAllLines(Paths.get(fileName));
    return lines;
  }

  public static void writeToTextFile(String fileName, String content) throws IOException {
    Files.write(Paths.get(fileName), content.getBytes(), StandardOpenOption.CREATE);
  }

}

  

To test these methods, create a text file called file.txt with some content in your project folder. Create the following Main class and run it.

package com.vogella.java.files;

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

public class Main {
  public static void main(String[] args) throws IOException {
    String input = FilesUtil.readTextFile("file.txt");
    System.out.println(input);
    FilesUtil.writeToTextFile("copy.txt", input);

    System.out.println(FilesUtil.readTextFile("copy.txt"));

    FilesUtil.readTextFileByLines("file.txt");
    Path path = Paths.get("file.txt");
  }
}

  

3. Reading resources out of your project / jar

You can read resources from your project or your jar file via the .getClass().getResourceAsStream() method chain from any object.

时间: 2024-10-09 01:45:58

Reading and writing files in Java (Input/Output) - Tutorial的相关文章

【DataStructure】A useful util class for reading and writing files

Faced with the upcoming exam, Some useful methods referred to file operation drew tremenous attention. Now I make a summary to reading file. [java] view plaincopy import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; impo

JAVA input/output 流层次关系图

在java中,input和output流种类繁多,那么它们之间是否有关系呢?答案是肯定的,其中使用到了设计模式,装饰模式 下图来自于HEAD FIRST 设计模式 装饰模式一章 下图来自网络博客:http://www.itzhai.com/java-based-notebook-io-flow-classification-and-detailed-description-of-various-classes-with-the-use-of-byte-stream-byte-stream-flo

Java Input/Output

java.util Scanner java.io PrintWriter Reader File InputStream/OutputStream Java的IO操作中有面向字节(Byte)和面向字符(Character)两种方式 参考: http://www.cnblogs.com/lanxuezaipiao/p/3371224.html

Exercise 16: Reading And Writing Files

from sys import argv script, filename = argv print "We're going to erase %r." % filename print "If you don't want that, hit CTRL-C (^C)." print "If you do want that, hit RETURN." raw_input("?") print "Opening t

Reading/Writing files with MSSQL‘s OPENROWSET

nfortunately, Microsoft SQL Server's SQL dialect Transact-SQL does not support reading and writing files in an easy way as opposed to MySQL's LOAD_FILE() function and INTO OUTFILEclause. Of course, with xp_cmdshell being enabled, you can read and wri

黑马程序员——java基础---IO(input output)流字符流

黑马程序员——java基础---IO(input output)流字符流 ------Java培训.Android培训.iOS培训..Net培训.期待与您交流! ------- io(input output)流特点: 1,io流用来处理数据之间的传输 2,java对数据的操作是通过流的方式: 3,java用于操作流的对象都在io包中: 4,流按操作数据分为两种:字节流和字符流: 5,流按流向分为:输入流和输出流. 注意:流只能操作数据,而不能操作文件. 3.IO流的常用基类: 1)字节流的抽象

JAVA学习分享Input Output

IO(Input  Output)流 IO流用来处理设备之间的数据传输 Java对数据的操作是通过流的方式 Java用于操作流的对象都在IO包中 流按操作数据分为两种:字节流与字符流. 流按流向分为:输入流,输出流. IO流常用基类 字节流的抽象基类: InputStream ,OutputStream. 字符流的抽象基类: Reader , Writer. 注:由这四个类派生出来的子类名称都是以其父类名作为子类名的后缀. (InputStream的子类FileInputStream.) (Re

数据库服务器Input/output error (故障20170122)

描述: 数据库系统出现告警,登陆查看使用系统命令报错,提示Input/output error 模拟故障处理过程: 检查文件系统时,该文件系统必须卸载.当出现错误时fsck会提示是否修复, 可以用-y参数:不提示是否修复 fsck - check and repair a Linux file system # df -h Filesystem            Size  Used Avail Use% Mounted on /dev/mapper/vg_mysql80-lv_root 2

解决NGINX+PHP-FPM failed to ptrace(PEEKDATA) Input/output error出错问题

网站总是出现bad gateway 提示,时有,时无,查看了一下日志,居然出现一堆错误,如下 [29-Mar-2014 22:40:10] ERROR: failed to ptrace(PEEKDATA) pid 4276: Input/output error (5) [29-Mar-2014 22:53:54] ERROR: failed to ptrace(PEEKDATA) pid 4319: Input/output error (5) [29-Mar-2014 22:56:30]