Java IO Tutorial — Java Files Content
Files.probeContentType(Path path) method probes the content type of a file.
The method returns the content type in the string form of the value of a Multipurpose Internet Mail Extension (MIME) content type.
If the content type of a file cannot be determined, it returns null.
The following code shows how to probe the content type of a file.
import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.io.IOException; /*from w ww.j ava 2s . c om*/ public class Main < public static void main(String[] args) < Path p = Paths.get("C:\\Java_Dev\\test1.txt"); try < String contentType = Files.probeContentType(p); System.out.format("Content type of %s is %s%n", p, contentType); > catch (IOException e) < e.printStackTrace(); >> >
The code above generates the following result.
Reading the Contents of a File
The Files class contains the following methods to read the contents of a file as bytes and lines of text:
- static byte[] readAllBytes(Path path) — reads all bytes from a file.
- static List readAllLines(Path path) — reads the entire contents of a file lines of text.
- static List readAllLines(Path path, Charset cs)
The Files class can obtain InputStream and BufferedReader objects from a Path object.
newInputStream(Path path, OpenOption. options) method returns an InputStream object for the specified path. It assumes that the file’s contents are in the UTF-8 charset.
The newBufferedReader(Path path) and newBufferedReader(Path path, Charset cs) method returns a BufferedReader. We can specify the charset.
The Files class provides methods to obtain a SeekableByteChannel object from a Path object using its newByteChannel(Path path, OpenOption. options) method.
OpenOption type configures the file being opened. The following table lists the values with their descriptions for the OpenOption type. OpenOption is an interface in the java.nio.file package.
The StandardOpenOption enum in the java.nio.file package implements the OpenOption interface.
StandardOpenOption | Description |
---|---|
APPEND | Appends the written data to the existing file, if the file is opened for writing. |
CREATE | Creates a new file, if it does not exist. |
CREATE_NEW | Creates a new file, if it does not exist. If the file already exists, it fails the operation. |
DELETE_ON_CLOSE | Deletes the file when the stream is closed. It is useful when used with a temporary file. |
DSYNC | Keeps the contents of the file synchronized with the underlying storage. |
READ | Opens a file with a read access. |
SPARSE | If it is used with the CREATE_NEW option, it is a hint to the file system that the new file should be a sparse file. |
SYNC | Keeps the content and the metadata of the file synchronized with the underlying storage. |
TRUNCATE_EXISTING | Truncates the length of an existing file to zero if the file is opened for a write access. |
WRITE | Opens a file for a write access. |
The following code obtains a SeekableByteChannel object for test2.txt file in the default directory.
It opens the file for a READ and WRITE access. It uses the CREATE option, so the file is created if it does not exist.
import static java.nio.file.StandardOpenOption.CREATE; import static java.nio.file.StandardOpenOption.READ; import static java.nio.file.StandardOpenOption.WRITE; import java.nio.channels.SeekableByteChannel; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class Main < public static void main(String[] args) throws Exception < Path src = Paths.get("test2.txt"); SeekableByteChannel sbc = Files.newByteChannel(src, READ, WRITE, CREATE); > >
The following code demonstrates how to read and display the contents of a file test1.txt in our default directory. The program displays an error message if the file does not exist.
import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.NoSuchFileException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; /*w w w .ja va2 s. co m*/ public class Main < public static void main(String[] args) throws Exception< Charset cs = Charset.forName("US-ASCII"); Path source = Paths.get("test1.txt"); List lines = Files.readAllLines(source, cs); for (String line : lines) < System.out.println(line); >> >
Writing to a File
We can use the following write() methods of the Files class to write contents to a file.
static Path write(Path path, byte[] bytes, OpenOption. options) static Path write(Path path, Iterable lines, OpenOption. options) static Path write(Path path, Iterable lines, Charset cs, OpenOption. options)
The write() method opens the file, writes the passed in contents to the file, and closes it.
If no open options are present, it opens the file with CREATE, TRUNCATE_EXISTING, and WRITE options.
If we are writing text to a file, it writes a platform-dependent line separator.
If charset is not specified when lines of text are written, UTF-8 charset is assumed.
The following code demonstrates how to write lines of texts to a file using the write() method.
import static java.nio.file.StandardOpenOption.CREATE; import static java.nio.file.StandardOpenOption.WRITE; /*from w w w .j a va 2 s . co m*/ import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; public class Main < public static void main(String[] args) < Listtexts = new ArrayList<>(); texts.add("test"); texts.add("test"); Path dest = Paths.get("twinkle.txt"); Charset cs = Charset.forName("US-ASCII"); try < Path p = Files.write(dest, texts, cs, WRITE, CREATE); System.out.println("Text was written to " + p.toAbsolutePath()); > catch (IOException e) < e.printStackTrace(); >> >
Files.newOutputStream(Path path, OpenOption. options) returns an OutputStream for the specified path.
Files.newBufferedWriter(Path path, Charset cs, OpenOption. options) method returns a BufferedWriter for the specified path.
The code above generates the following result.
Random Access to a File
A SeekableByteChannel object provides random access to a file.
We can get a SeekableByteChannel object for a Path using the newByteChannel() method of the Files class as follows:
Path src = Paths.get("test.txt"); SeekableByteChannel seekableChannel = Files.newByteChannel(src, READ, WRITE, CREATE, TRUNCATE_EXISTING);
We can get the size of the entity of a SeekableByteChannel in bytes using its size() method.
As the data is truncated or written to the channel, the size is updated.
Content repository API for Java
Content Repository API for Java(JCR) — это специализированый API на java платформе для доступа к Content Repository. Подобные системы чаще всего используются для хранения данных и метаданных в Система_управления_содержимым (CMS). Спецификация была разработана в рамках Java_Community_Process и имеет номер JSR-170 в первой версии и JSR-283 во второй. Основной пакет — javax.jcr.
JCR — один из типов объектной базы данных, созданных для хранения, поиска и извлечения иерархических данных. JCR API выросло из нужд систем управления контентом, для которых необходимо сохранение двоичных объектов и ассоциированных с ними метаданных. Кроме интерфейса для хранения также предоставляется интерфейс версионирования данных, транзакционности и отслеживания изменений.
Данные в JCR представляют собой дерево, состоящее из узлов с ассоциированными с ними свойствами. Эти свойства и являются хранимыми данными, и могут хранить строки, числа, двоичные данные, изоображения итд. Узлы также могут ссылаться на другие узлы с помощью специальных ссылок.
Wikimedia Foundation . 2010 .
Смотреть что такое «Content repository API for Java» в других словарях:
- Content repository API for Java — (JCR) is a specification for a Java platform application programming interface (API) to access content repositories in a uniform manner.[1][dead link][2][not in citation given] … Wikipedia
- Content repository — A content repository is a store of digital content with an associated set of data management, search and access methods allowing application independent access to the content, rather like a digital library, but with the ability to store and… … Wikipedia
- Content Repository for Java Technology API — (JCR) ist eine Spezifikation für eine Java Plattform API, um auf Content in einer einheitlichen Methode zuzugreifen.[1][2] Content Repositories werden von den unterschiedlichsten Informationssystemen genutzt, die beliebige Dokumente zusammen mit… … Deutsch Wikipedia
- Java Specification Request — Java Specification Requests Java Specification Requests (JSR) est un système normalisé ayant pour but de faire évoluer la plateforme Java. Sommaire 1 Présentation 2 Implémentation 3 Interopérabilité informatique … Wikipédia en Français
- Java Specification Requests — (JSR) est un système normalisé ayant pour but de faire évoluer la plateforme Java. Sommaire 1 Présentation 2 Implémentation 3 Liste des JSRs 4 Notes et … Wikipédia en Français
- Java (значения) — … Википедия
- Java Specification Request — Ein Java Specification Request (JSR) ist eine Anforderung einer neuen Java Spezifikation oder einer wichtigen Änderung einer existierenden Java Spezifikation, die im Rahmen des Java Community Process (JCP) an das von Sun Microsystems betriebene… … Deutsch Wikipedia
- Java 4K Game Programming Contest — The Java 4K Game Programming Contest (aka Java 4K and J4K ) is an informal contest that was started by the Java Game Programming community to challenge their software development abilities. The goal of the contest is to develop the best game… … Wikipedia
- Liste de systèmes de gestion de contenu — Cet article présente une liste de systèmes de gestion de contenu (SGC). Article principal : Système de gestion de contenu. Sommaire 1 Quelques SGC 1.1 SGC ne nécessitant pas de base de données 1.2 Portails … Wikipédia en Français
- Liste De Systèmes De Gestion De Contenu — Cet article présente une liste de systèmes de gestion de contenu (SGC). Article détaillé : Système de gestion de contenu. Sommaire 1 Quelques SGC 1.1 SGC ne nécessitant pas de base de données 1.2 Portails … Wikipédia en Français