File input output in java

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

Java provides the java.nio.file API to read and write files. 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. The usage of this method is demonstrated in the following listing.

import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; // somewhere in your code String content = Files.readString(Path.of("resources", "work", "input.xml"));

To read a text file line by line into a List of type String structure you can use the Files.readAllLines method.

ListString> lines = Files.readAllLines(Paths.get(fileName));

Files.readAllLines uses UTF-8 character encoding. It also ensures that file is closed after all bytes are read or in case an exception occurred.

1.3. Reading and filtering line by line

The Files.lines method allows read a file line by line, offering a stream. This stream can be filtered and mapped. Files.lines does not close the file once its content is read, therefore it should be wrapped inside a try-with-resource statement.

In the following example unnecessary whitespace at the end of each line is removed and empty lines are filterer.

//read all lines and remove whitespace (trim) //filter empty lines //and print result to System.out Files.lines(new File("input.txt").toPath()) .map(s -> s.trim()) .filter(s -> !s.isEmpty()) .forEach(System.out::println);

The next example demonstrates how to filter out lines based on a certain regular expression.

Files.lines(new File("input.txt").toPath()) .map(s -> s.trim()) .filter(s -> !s.matches("yourregularexpression")) .forEach(System.out::println);

The next example extracts a line starting with «Bundle-Version:» from a file called MANIFEST.MF located in the META-INF folder. It removes the prefix and removes all leading and trailing whitespace.

package com.vogella.eclipse.ide.first; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Optional; import java.util.stream.Stream; public class ReadMANIFESTFile  public static void main(String[] args) throws IOException  String versionString = readStreamOfLinesUsingFiles(); System.out.println(versionString); > private static String readStreamOfLinesUsingFiles() throws IOException  StreamString> lines = Files.lines(Paths.get("META-INF", "MANIFEST.MF")); OptionalString> versionString = lines.filter(s -> s.contains("Bundle-Version:")).map(e-> e.substring(15).trim()).findFirst(); lines.close(); if (versionString.isPresent())  return versionString.get(); > return ""; > >

1.4. Writing a file in Java

To write a file you can use the following method:

Files.write(stateFile.toPath(), content.getBytes(StandardCharsets.UTF_8), StandardOpenOption.CREATE);

1.5. List all files and sub-directories using Files.list()

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

// writes all files of the current directory Files.list(Paths.get(".")).forEach(System.out::println);

1.6. How to identify the current directory

String currentDir = 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 ListString> readTextFileByLines(String fileName) throws IOException  ListString> 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. Example: Recursively listing all files of a diretory

Java 8 provides a nice stream to process all files in a tree.

Files.walk(Paths.get(path)) .filter(Files::isRegularFile) .forEach(System.out::println);

4. Example: Deleting a directory with all subdirectories and files

To delete a directory and all its content.

String stringPath=". yourPath. "; Path path = new File(stringPath).toPath(); Files.walk(path) .sorted(Comparator.reverseOrder()) .map(Path::toFile) .forEach(File::delete);

5. 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.

Источник

Java: File Input and Output

When data items are stored in a computer system, they can be stored for varying periods of time—temporarily or permanently.

  • Temporary storage is usually called computer memory or random access memory (RAM). When you write a Java program that stores a value in a variable, you are using temporary storage; the value you store is lost when the program ends or the computer loses power. This type of storage is volatile.
  • Permanent storage, on the other hand, is not lost when a computer loses power; it is nonvolatile. When you write a Java program and save it to a disk, you are using permanent storage.

Files exist on permanent storage devices, such as hard disks, Zip disks, USB drives, reels or cassettes of magnetic tape, and compact discs .Computer files are the electronic equivalent of paper files often stored in file cabinets in offices.

When you work with stored files in an application, you typically perform all or some of the following tasks:

  • Determining whether and where a file exists
  • Opening a file
  • Reading data from a file
  • Writing information to a file
  • Closing a file

USING THE File CLASS

You can use Java’s File class to gather file information, such as its size, its most recent modification date, and whether the file even exists. You must include the following statement to use the File class:

The java.io package contains all the classes you use in file processing, so it is usually easiest to import the entire package using the wildcard * character, as follows:

The File class is a subclass of the Object class. You can create a File object using a constructor that includes a filename as its argument, for example, you make the following statement when Data.txt is a file on the project root folder:

File fileName = new File("Data.txt");

Below is the list of some of important File class methods with purpose and method signature

Method name/Signature Purpose
boolean canRead() Returns true if a file is readable
boolean canWrite() Returns true if a file is writable
boolean exists() Returns true if file exists
String getName() Returns file name
String getPath() Returns the file’s path
String getParent() Returns the name of the folder in which the file can be found
long length() Returns the file’s size
long lastModified() Returns the time the file was last modified; this time is system dependent and should be used only for comparison with other files’ times, not as an absolute time
boolean isDirectory( ) When you create a File object and it is a directory, the isDirectory( ) method will return true.

Let’s understand these method’s implementation with help of java program. In the main()method, a File object named myFile is declared. The String passed to the constructor is “SomeData.txt”, which is the stored file’s system name. In other words, although SomeData.txt might be the name of a stored file when the operating system refers to it, the file is known as myFile within the application. We need to create Data.txt file in project root directory else we will get a message saying “File does not exist”.

import java.io.File; public class FileClassMethods < public static void main(String[] args) < File myFile = new File("Data.txt"); if (myFile.exists()) < System.out.println(myFile.getName() + " exists"); System.out.println("The file is " + myFile.length() + " bytes long"); if (myFile.canRead()) System.out.println(" ok to read"); else System.out.println(" not ok to read"); if (myFile.canWrite()) System.out.println(" ok to write"); else System.out.println(" not ok to write"); System.out.println("path: " +myFile.getAbsolutePath()); System.out.println("File Name: "+ myFile.getName()); System.out.println("File Size: "+ myFile.length() + " bytes"); >else System.out.println("File does not exist"); > > 

If file is not available in project root folder.

directory structure image

when the file is present:

directory structure image

Handling Exceptions

Several exceptions in the java.io package might occur when you are working with files and streams.

  • A FileNotFound exception occurs when you try to create a stream or file object using a file that couldn’t be located.
  • An EOFException indicates that the end of a file has been reached unexpectedly as data was being read from the file through an input stream.

These exceptions are subclasses of IOException. One way to deal with all of them is to enclose all input and output statements in a try-catch block that catches IOException objects. Call the exception’s toString() or getMessage() methods in the catch block to find out more about the problem

  • All real life application generates lots of data which need to be referred at a later stage. This requirement is achieved using File storage on a permanent storage device like a disk drive, CD ROM, pen drive etc.
  • Java provides a library of classes to access this permanently stored information on files called FileIO or java.io. * Package.
  • java.io.File class provides some of the very useful utility methods like permission checking, file size checking, absolute path checking etc.

Java Code Editor:

Follow us on Facebook and Twitter for latest update.

  • Weekly Trends
  • Java Basic Programming Exercises
  • SQL Subqueries
  • Adventureworks Database Exercises
  • C# Sharp Basic Exercises
  • SQL COUNT() with distinct
  • JavaScript String Exercises
  • JavaScript HTML Form Validation
  • Java Collection Exercises
  • SQL COUNT() function
  • SQL Inner Join
  • JavaScript functions Exercises
  • Python Tutorial
  • Python Array Exercises
  • SQL Cross Join
  • C# Sharp Array Exercises

We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook

Источник

Читайте также:  Последний элемент строки python
Оцените статью