Java Output stream FileOutputStream The use of,

http://baijiahao.baidu.com/s?id=1600984799323133994&wfr=spider&for=pc


I've explained how to apply the input stream FileInputStream Reading data from a local file . This section describes the application output stream FileOutputStream Write data to a local file .

use FileOutputStream The writing process is as follows :

Use FileOutputStream The process of writing a file is the same as using FileInputStream The process is the same , It's all used first File Class to open a local file , Instantiate input and output streams , Then the read and write method of the stream is called to read or write data , Finally, close the flow .

FileOutputStream Construction method of

FileOutputStream Provides 4 A common construction method , Used to instantiate FileOutputStream object , Different scenes use different construction methods .

scene 1: Use File Object to open a local file , Read data from file .

scene 2: Don't use File object , Pass in the file path directly .

FileOutputStream The construction method of allows you to pass in the file path directly , Instead of using File object . View the source code of the constructor , It uses... Internally File Object to open the file .

scene 3: Open file , Add write data at the end of the file .

The scenario requires writing data at the end of the file , Since the first two constructors are both files, start writing data ( Overwrite the original file ), So you can't use the front 2 The constructor of a scene .FileOutputStream Two other construction methods are provided , Namely :

FileOutputStream(File file, boolean append);

FileOutputStream(String name, boolean append);

Compared with the previous construction method , One more of these two construction methods boolean Parameters append.append Parameter is true when , Data is written from the end of the file ;append Parameter is false when , Data overlay the original file .

FileOutputStream Write method of

FileOutputStream Class provides a variety of file writing methods , You can write a single byte to a file , You can also write a byte Array to file , Can also take byte Part of the data of the array is written to a file .

example 1: Use write(int b) Method write file .

The example program first calls File Class createNewFile() establish new.txt file , And then str The content is written to the newly created new.txt In file .

example 2: Use write(byte[] b) Method write file .

write(byte[] b) Method is used to b.length Bytes from the specified byte Array is written to the output stream .

String Class getBytes() Method to convert a string to byte Array , Use FileOutputStream Class write(byte[] b) Method , Will be transformed byte Array write to file .

example 3: Use write(byte[] b,int off,int len) Method write file .

This method will len Bytes of data , And from the array b Of off Position starts writing to the output stream .

The program puts the specified str Write content to a file ,fos.write(str.getBytes(),5,10) The first argument to the statement is byte Array , The second parameter 5 It's from byte Index of the array 5 Start , The third parameter is the number of bytes written . After the program is executed , The content written is “is new file”.

When using this method, we must pay attention to the problem of array out of bounds . for example ,byte The array length is 20, From the second subscript 12 Start , write in 15 Bytes to file , It will cause the array to go out of bounds , Application error .

example 4: Use FileOutputStream Copy file

Copying a file is writing data from the source file to a new file , In actual programming , There are many ways to copy files , Use in this case FileInputStream and FileOutputStream Realize file copying .

In code copyFile Finish copying the file , Before copying , First determine whether the source file exists , Then apply for a byte Array , Used to store read source file data , The size of the array is the same as the total number of bytes in the source file , After successful reading , Then write the contents of the array to the target file . The output of the program is shown in the figure below :

■ Knowledge dissemination

Use FileOutputStream Stream can write byte data to the target file ,FileOutputStream Provides single byte write and byte There are two ways to write arrays . It is recommended to use byte Array write , Store the data to be written in a byte Array , Then write to the file . When the written file already exists , You need to indicate whether the write method is overlay or append .

Java Output stream FileOutputStream Use more related articles in detail

  1. java Network programming (TCP Detailed explanation )

    Detailed explanation of network programming -TCP One ,TCP The features of the agreement               Connection oriented protocol ( If there is a sender, there must be a receiver )    Establish a connection through three connection handshakes Disconnect with four handshakes be based on IO Streaming data Transfer data size ...

  2. Java 8 Stream API Detailed explanation -- turn

    Original address :http://blog.csdn.net/chszs/article/details/47038607 Java 8 Stream API Detailed explanation One .Stream API Introduce Java8 Introduced ...

  3. java In depth explanation of reflection mechanism

    java In depth explanation of reflection mechanism   from :http://www.cnblogs.com/hxsyl/archive/2013/03/23/2977593.html One . Concept Reflection is to Java The various components of ...

  4. internationalization ,java.util.ResourceBundle The use of,

    java.util.ResourceBundle The use of,   One . Understanding international resource documents   This class provides a shortcut to internationalization of software . Through this , Can make the program that you write can :          Easily localize or translate into different languages ...

  5. java And StringBuffer Class explanation

    StringBuffer Thread safe variable character sequence . StringBuffer Source code analysis (JDK1.6): public final class StringBuffer extends Abstract ...

  6. java.util.ResourceBundle The use of,

    java.util.ResourceBundle The use of,   One . Understanding international resource documents   This class provides a shortcut to internationalization of software . Through this , Can make the program that you write can :          Easily localize or translate into different languages ...

  7. java And AbstractStringBuilder Class explanation

    Catalog AbstractStringBuilder class Field Constructors Method   public abstract String toString() Expand capacity void  expandCapacity(in ...

  8. java And StringBuilder Class explanation

    StringBuilder Non thread safe variable character sequence  . This class is designed to be used as StringBuffer A simple replacement of , When the string buffer is used by a single thread ( It's very common ). If possible , It is recommended that such , Because in ...

  9. java.util.ResourceBundle The use of, ( turn )

    java.util.ResourceBundle The use of,   One . Understanding international resource documents   This class provides a shortcut to internationalization of software . Through this , Can make the program that you write can :          Easily localize or translate into different languages ...

Random recommendation

  1. The finger of the sword Offer Interview questions :28. The maximum sum of successive subarrays

    One . subject : The maximum sum of successive subarrays subject : Enter an integer array , There are positive and negative numbers in the array . One or more consecutive integers in an array form a subarray . Find the maximum sum of all subarrays . The required time complexity is O(n). For example, the input array is {1,-2,3 ...

  2. C# entrust (Action、Func、predicate)

    Predicate Commissioned by the generic : Represents a method that defines a set of conditions and determines whether a specified object meets those conditions . This Commission is made by Array and List Several methods of using class , Used to search for elements in a collection . public delegate boo ...

  3. HYSBZ 2440 Complete square ( Mobius inversion )

    link :http://www.lydsy.com/JudgeOnline/problem.php?id=2440 if i Prime number ,n by i*i Multiple , said n Is the number with square factor . seek 1~n The square free number of . F(x) ...

  4. Ping-Pong (Easy Version)(DFS)

    B. Ping-Pong (Easy Version) time limit per test 2 seconds memory limit per test 256 megabytes input ...

  5. ecmall widgets Details of pendant development

    Ecmall Pendant development In essence, it's the background development of many pages , Call the program to display these pages , Achieve the purpose of changing the content of the home page quickly , This reduces subsequent development , Developers just need to develop the pendant , As for the position, it can be decided at will .( It needs to be adjusted html, But at least ...

  6. EF Data modeling ( One )

    It is often used in large and medium-sized software development ORM technology ,ORM The full name is “ object - Relation mapping Object-Relation-Mappping”. It is to show the form of data object in the database , And will organize these objects in an object-oriented way , ...

  7. The Karting 2017ccpc Online games 1008

    The Karting championship will be held on a straight road. There are N keypoints on the road. The pat ...

  8. js Some practical skills to use

    1.jquery In the page timing call ajax Method function SetContinueSend(param1,param2, func){ func.call(null,param1,param2) } ...

  9. mysql-8.0.12 install + To configure , Navicat Premium 12 install + Activate

    1. Unzip to the installation directory , Such as :D:\mysql-8.0.12-winx64 2. Paste the following configuration file into the installation directory , And save for my.ini, Be careful : Use ansi Instead of utf-8 The encoding format is saved [mysql] # Set up m ...

  10. ASP.NET Core in ,UseDeveloperExceptionPage Extension methods eat exceptions

    stay ASP.NET Core in Startup Class Configure In the method , There's an extension called UseDeveloperExceptionPage, As shown below : // This method gets call ...