Read and write to the file is always my weak link, this is caused by the wrong learning habits: each course I began to learn very seriously, so the foundation is relatively solid point; but then the more the more relaxed, so the next one becomes blurred, and the Java curriculum I/O Also put in the back position to introduce, so this piece of learning is not good ...
This morning I was looking at "Ivor Horton's beginning Java 2, JDK 5 Edition" ("Java 2 Getting Started"), and wrote several examples.
First look at how FileInputStream is described in the API:
The public class Fileinputstreamextends Inputstreamfileinputstream gets the input bytes from a file in the file system. Which files are available depends on the host environment.
FileInputStream is used to read raw byte streams such as image data. To read character streams, consider using FileReader.
FileInputStream (File file): Creates a fileinputstream by opening a connection to the actual file, which is specified by file object filename in the filesystem.
FileInputStream (FileDescriptor fdobj): Creates a fileinputstream by using the file descriptor Fdobj, which represents an existing connection to an actual file in the file system.
FileInputStream (String name): Creates a fileinputstream by opening a connection to the actual file, which is specified through the pathname name in the file system.
The following example uses a channel to write a string to a file.
Package Com.bulaoge.alenc;
Import Java.io.File;
Import Java.io.FileOutputStream;
Import java.io.IOException;
Import java.io.FileNotFoundException;
Import Java.nio.ByteBuffer;
Import Java.nio.channels.FileChannel;
/**
* @title Writeastring.java
* @author Alenc
*/
public class writeastring ... {
public static void Main (string[] args) ... {
String phrase = new string ("Garbage in, Garbage out");
String dirname = "c:/";
String filename = "OUT.txt";
File dir = new file (dirname);
Check out the directory
if (!dir.exists ()) ... {
if (!dir.mkdir ()) ... {
System.out.println ("Cannot creat directory:" + dirname);
System.exit (1);
}
else if (!dir.isdirectory ()) ... {
System.out.println (dirname + "is not a director");
System.exit (1);
}
Creat the FileStream
File Afile