Q:
程序如下:
FileOutputStream output = new FileOutputStream("d:\\a.txt");
output.write(97);
output.close();
如果我原来的 d:\a.txt中有内容 asdfasdfasdfa
怎么样才能将 ascii码97的a添加到 文件内容后面?
有没有相应的API啊
我也想到先将文件内容取到StringBuilder,然后将a后缀到StringBuilder,我觉得应该又更好的办法,能用JDK API上的东西就用API上的东西
A:
有重载构造方法的!
public FileOutputStream(FileDescriptor fdObj)
- Creates an output file stream to write to the specified file descriptor, which represents an existing connection to an actual file in the file system.
First, if there is a security manager, its
checkWrite
method is called with the file descriptorfdObj
argument as its argument. - Parameters:
fdObj
- the file descriptor to be opened for writing- Throws:
SecurityException
- if a security manager exists and itscheckWrite
method denies write access to the file
descriptor- See Also:
SecurityManager.checkWrite(java.io.FileDescriptor)
Example:
FileOutputStream output = new FileOutputStream("d:\\a.txt",true);
Example:
/* Append output to file using FileOutputStream This example shows how to append byte data to a file using write method of Java FileOutputStream object. */ import java.io.*; public class AppendToFile { public static void main(String[] args) { String strFilePath = "C://FileIO//demo.txt"; try { /* * To append output to a file, use * FileOutputStream(String file, booean blnAppend) or * FileOutputStream(File file, booean blnAppend) constructor. * * If blnAppend is true, output will be appended to the existing content * of the file. If false, file will be overwritten. */ FileOutputStream fos = new FileOutputStream(strFilePath, true); String strContent = "Append output to a file example"; fos.write(strContent.getBytes()); /* * Close FileOutputStream using, * void close() method of Java FileOutputStream class. * */ fos.close(); } catch(FileNotFoundException ex) { System.out.println("FileNotFoundException : " + ex); } catch(IOException ioe) { System.out.println("IOException : " + ioe); } } }