New features of Java SE 7 file operations (6) - create a file and read the file

2010-04-03  来源:本站原创  分类:Java  人气:540 

Transferred from the developer's sky

In this paper we discuss how to create files in NIO2 in, read the file and write files. NIO2 offers a variety of methods to create documents, allows us to create the file when you can specify some initial attributes file. For example, in support of the POSIX file system on the specified file owner, access rights and so on. On the file's properties, see the article on the new features of Java SE 7 file operations (5) - metadata management
<br /> Can create a file called createFile (FileAttribute <?>) Method creates an empty file. The method parameter is the initial document properties. The following example is how to create a file when given certain privileges to the file properties:

If the method is called when no arguments are passed, then the created file will have the default file attributes. The following code creates a file with default file attributes:

Path file = ...;
try {
    file.createFile();   //Create the empty file with default permissions, etc.
} catch (FileAlreadyExists x) {
    System.err.format("file named %s already exists%n", file);
} catch (IOException x) {
    //Some other sort of failure, such as permissions.
    System.err.format("createFile error: %s%n", x);
}

If you want to create the file already exists, this method throws an exception.
Note that the call createFile method, check the file exists and create a file with a specific property is in the same atomic operation.
You can also use newOutputSteam method to create the file, later in this article we will talk about how to use newOutputStream method to create the file.
By Stream I / O read file <br /> we can newInputStream (OpenOption. ..) method to open and read documents. This method returns an unbuffered input stream (input stream), we can use it to read bytes from the file content.

Path file = ...;
InputStream in = null;
try {
    in = file.newInputStream();
    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    String line = null;
    while ((line = reader.readLine()) != null) {
        System.out.println(line);
    }
} catch (IOException x) {
    System.err.println(x);
} finally {
    if (in != null) in.close();
}

Note that the method accepts a variable number of parameters, parameter type OpenOption, how to open the file specified. If you do not pass parameters, use the default READ opened. READ mode is all the way to achieve support. Some implementation also support other Open.
If the combination of the incoming OpenOption or incorrect, will throw an exception. If the program does not read permission, or I / O errors will be thrown.
Creating and Writing a File by Using Stream I / O
Using the Stream I / O to create and write files <br /> We can use newOutputStream method to create a file, expanding files or overwrite existing files. This method to write files to open or create the file, the method returns an unbuffered output stream (output stream). newOutputStream method has two forms:

  • newOutputStream (OpenOption. ..)
  • newOutputStream (Set <? extends OpenOption>, FileAttribute <?>...)

Both forms are acceptable as a OpenOption parameters, the second form also allows you to specify the initial file attributes. This approach supports the StandardOpenOption are:

  • WRITE - to write access and open the file.
  • APPEND - new data will extend the end of the file. The options and WRITE or CREATE option.
  • TRUNCATE_EXISTING - file truncated to 0 bytes long. WRITE option with this option and use to overwrite the original file.
  • CREATE_NEW - Create a new file. If the original documents exist throws an exception.
  • CREATE - If the original file exists it opens it, or create a new file.
  • DELETE_ON_CLOSE - Stream closed as delete the file. This option is more useful for temporary files.
  • SPARSE - show that the newly created file is Sparse file. On Sparse file specific information see http://space.itpub.net/8242091/viewspace-619756 .
  • SYNC - to keep the file (including content and metadata) and the underlying storage devices simultaneously.
  • DSYNC - to keep the document with the underlying storage devices simultaneously.

If not specified OpenOption, the behavior of this method is: if the file does not exist, then create a new file; if the file exists, then cut it. That is the default option is a combination of CREATE and TRUNCATE_EXISTING options.
The following code opens a log file, if the file does not exist, then create a new file. If the file exists, this new content will be extended to end of the file.

import static java.nio.file.StandardOpenOption.*;

Path logfile = ...;

//Convert the string to a byte array.
String s = ...;
byte data[] = s.getBytes();

OutputStream out = null;
try {
    out = new BufferedOutputStream(logfile.newOutputStream(CREATE, APPEND));
    ...
    out.write(data, 0, data.length);
} catch (IOException x) {
    System.err.println(x);
} finally {
    if (out != null) {
        out.flush();
        out.close();
    }
}


Using the Channel I / O to read and write files
Stream I / O time to read a character, Channel I / O buffer for each read a block of data. ByteChannel interface provides the basic read and write functions. SeekableByteChannel extends ByteChannel, and provides a channel to maintain the position and the ability to change the location. SeekableByteChannel also supports the truncated file and check the file size of the feature.
Moved to a different file location, starting from the position the ability to read or write so that we can randomly access files. There are two forms of newByteChannel method can be used to read or write files, both the same way as the form and newOutputStream.

  • newByteChannel (OpenOption. ..)
  • newByteChannel (Set <? extends OpenOption>, FileAttribute <?>...)

Both methods allow you to specify OpenOption, newOutputStream supported the choice of support here, too, and there is also support for another option READ, because SeekableByteChannel supports both reading supports writing.
If the option is READ, then the channel is open for read access. If the option is WRITE or APPEND, then the channel is open for write access. If not specified, the default is to read the channel open.
The following code read from the file content and output to the console:

SeekableByteChannel sbc = null;
try {
    sbc = file.newByteChannel();  //Defaults to READ
    ByteBuffer buf = ByteBuffer.allocate(10);

    //Read the bytes with the proper encoding for this platform.
    //If you skip this step, you might see something that looks like Chinese
    //characters when you expect Latin-style characters.
    String encoding = System.getProperty("file.encoding");
    while (sbc.read(buf) > 0) {
        buf.rewind();
        System.out.print(Charset.forName(encoding).decode(buf));
        buf.flip();
    }
} catch (IOException x) {
    System.out.println("caught exception: " + x);
} finally {
    if (sbc != null) sbc.close();
}

The following code is a UNIX or other support for POSIX file systems prepared. This code creates a new log file or the expansion of the original log files, the log file created when the specified access rights (owner has read and write permissions, only read access to the same group of users, other users do not have read access).

import static java.nio.file.StandardCopyOption.*;

//Create the set of options for appending to the file.
Set<OpenOptions> options = new HashSet<OpenOption>();
options.add(APPEND);
options.add(CREATE);

//Create the custom permissions attribute.
Set<PosixFilePermission> perms = PosixFilePermissions.fromString("rw-r------");
FileAttribute<Set<PosixFilePermission>> attr = PosixFilePermissions.asFileAttribute(perms);

//Convert the string to a ByetBuffer.
String s = ...;
byte data[] = s.getBytes();
ByteBuffer bb = ByteBuffer.wrap(data);

SeekableByteChannel sbc = null;
try {
    sbc = file.newByteChannel(options, attr);
    sbc.write(bb);
} catch (IOException x) {
    System.out.println("exception thrown: " + x);
} finally {
    if (sbc != null) sbc.close();
}
相关文章
  • New features of Java SE 7 file operations (6) - create a file and read the file 2010-04-03

    Transferred from the developer's sky In this paper we discuss how to create files in NIO2 in, read the file and write files. NIO2 offers a variety of methods to create documents, allows us to create the file when you can specify some initial attribut

  • New features of Java SE 7 file operations (9) - traverse the directory tree 2010-04-13

    Transferred from the developer's sky In some cases, we may need to traverse the entire directory tree, such as the need to find all. Java file. Java SE 7 provides a very convenient way to achieve this kind of functionality. Implementation of Java SE

  • New features of Java SE 7 file operations (3) - some of the concepts related to 2010-03-29

    Transferred from the developer's sky Path class provides many methods to files and directories to read, write and other operations. Look at these methods, we first need to understand some of the other concepts: Varargs Varargs actually stands for Var

  • New features of Java SE 7 file operations (4) - delete. Copy and move files 2010-03-30

    <! - @ Page (size: 8.27in 11.69in; margin: 0.79in) P (margin-top: 0in; margin-bottom: 0.08in) -> Transferred from the developer's sky Deletion Through the Path class, we can remove the files, directories or symbolic links. Note that when we remove t

  • Java SE 6 new features: Instrumentation 2010-11-25

    (From http://baike.baidu.com/view/1589420.html) Java SE 6 new features: Instrumentation, using Java code, that is, for dynamic Instrumentation java.lang.instrument is the new features of Java SE 5, which functions to instrument Java, freed from the l

  • Java file operations enhancement tools 2010-03-29

    Java file operations enhancement tools -------------------------------------------------- ------------------------------ 2008-12-15 18:30:43 Tags: File IO commons [pushed to the technical ring] Copyright Statement: original works, and if reproduced,

  • Maple wind ASP class file operations (FSO) (change) 2010-05-04

    '============================================================= ' Author : Maple leaves were 'QQ:455948725 'E-mail:[email protected] 'WebSite:http://www.fengyekun.com '============================================================= class FsoClass privat

  • 3) Linux Programming Introduction - File Operations 2010-09-26

    Files under Linux operating Introduction: In this section we will discuss the various file operations under linux function. File creation and read-write Each attribute Directory file operation Pipe File -----------------------------------------------

  • Java SE 7 file operations (1)-Path Class Description 2010-03-24

    Taken from the developers of the Sky 1. Path of the concept of <br /> file system files will be organized and stored in medium, usually one or more of the hard disk. Currently, most of the file system tree is a way to store documents. In the top of

  • Java file operations method 2010-03-29

    Transfer from the following code: http://lionelxx777.javaeye.com/blog/358128 Java file operations to the text of the two methods. 1. The usual practice is to use FileInputStream and FileOutputStream to carry out operations, the above two categories r

  • Java file operations 2010-03-29

    This collection of common file operations methods, including file creation / check and delete, directory creation / check and delete, remove files in the directory, file properties to acquire, read data line by line and so on. Documents establish / c

  • Java file operations on the Properties Summary 2010-05-13

    Frequently used, Java file operations on the Properties, to make a summary here. Java Properties files on the operation to be "unsatisfactory", said here about the first time in general, back slowly said. 1.java read Properties files, often worn

  • JAVA write file operations Gadgets 2010-12-13

    Long time no written code, very, very strange, a lot of things are forgotten, wrote a small tool that small problem there, get me a whole night, and later that knows the problem, but it still is in view of solving complex, thought did not need a gadg

  • java file operations to read and write basic 2011-01-11

    package com.hzsuwang.java; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java

  • java file operations Considerations (lesson) 2010-03-29

    File Handling Precautions 1) In order to process robustness, please check the file before the file operations to the parent directory (parentfolder) exists. File folder = new File (parentfolder_path) if (! folder.isDirectory ()) (/ / use the director

  • java programming source code file operations thought IO6 2010-05-05

    package com.dirlist; import java.io.BufferedReader; import java.io.IOException; import java.io.PrintWriter; import java.io.StringReader; public class FileOutputShortcut { /** * The shortcut text file output */ static String file="FileOutputShortcut.o

  • java file operations Daquan 2010-06-09

    1. Get the information entered by the user console Java code / ** *//** Get the information entered by the user console * @ Return * @ Throws IOException * / public String getInputMessage () throws IOException ... ( System.out.println ("Please enter

  • java file operations (recursive delete the empty folder, delete the expired file) 2010-09-19

    The operation of the document, we all write operations may, in fact, Apache, FileUtils has done a very good package, commonly used today's operational records are as follows: (1) to retain records of a few months before the provisions are as follows:

  • Java file operations (transfer) 2010-10-10

    One. Get the console user input / ** Get the information entered by the user console * @ Return * @ Throws IOException * / public String getInputMessage () throws IOException { System.out.println ("Please enter your command:"); byte buffer [] =

  • Java file operations Daquan read and write 2010-11-14

    One. Get the console user input / ** *//** Get the console user input * @ Return * @ Throws IOException * / public String getInputMessage () throws IOException ... { System.out.println ("Please enter your command:"); byte buffer [] = new byte [1