package think.in.java.io;
import java.io.IOException;
import java.io.StringReader;
/**
* read( ) returns the next character as an int and thus it must be cast to a char to print properly.
* @author WPeng
* @since 2012-11-5
*/
public class MemoryInput {
public static void main(String[] args) throws IOException{
StringReader in = new StringReader(BufferedInputFile.read("MemoryInput.java"));
int c;
while((c = in.read()) != -1){
System.out.println(c);
System.out.println((char)c);
}
}
}
package think.in.java.io;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.EOFException;
import java.io.FileInputStream;
import java.io.IOException;
/**
* DataInputStream, which is a byteoriented I/O class (rather than char-oriented).
* Thus you must use all InputStream classes rather than Reader classes.
*
* 典型的装饰者模式 - decorator pattern
* available( ) method to find out how many more characters are available.
* Here’s an example that shows how to read a file one byte at a time:
* @author WPeng
*
* @since 2012-11-5
*/
public class FormattedMemoryInput {
public static void main(String[] args) throws IOException{
try {
DataInputStream in =
new DataInputStream(
new ByteArrayInputStream(
BufferedInputFile.read("FormattedMemoryInput.java").getBytes()));
while(true){
System.out.print((char)in.readByte());
}
} catch (EOFException e) {
// TODO: handle exception
}
DataInputStream in =
new DataInputStream(
new BufferedInputStream(
new FileInputStream("FormattedMemoryInput.java")));
while(true){
System.out.print((char)in.readByte());
}
}
}
package think.in.java.io;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringReader;
/**
* want to buffer the output by wrapping it in a BufferedWriter.
* this wrapping dramatically increase performance of I/O operations.
* @author WPeng
*
* @since 2012-11-5
*/
public class BasicFileOutput {
static String file = "BasicFileOutput.out";
static String file_2 = "FileOutputShortcut.out";
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(
new StringReader(
BufferedInputFile.read("BasicFileOutput.java")));
// PrintWriter -> BufferedWriter
PrintWriter out = new PrintWriter(
new BufferedWriter(new FileWriter(file)));
int lineCount = 1;
String s;
while ((s = in.readLine()) != null)
out.println(lineCount++ + ": " + s);
/**
* You’ll see an explicit close( ) for out,
* because if you don’t call close( ) for all your output files,
* you might discover that the buffers don’t get flushed,
* so the file will be incomplete.
*/
out.close();
// Show the stored file:
System.out.println(BufferedInputFile.read(file));
/**
* Java SE5 added a helper constructor to PrintWriter
* so that you don’t have to do all the decoration by hand
* every time you want to create a text file and write to it.
*/
// Here’s the shortcut:
PrintWriter out_2 = new PrintWriter(file_2);
int lineCount_2 = 1;
String s_2;
while((s_2 = in.readLine()) != null )
out_2.println(lineCount_2++ + ": " + s_2);
out_2.close();
// Show the stored file:
System.out.println(BufferedInputFile.read(file_2));
}
}
package think.in.java.io;
import java.io.IOException;
import java.io.RandomAccessFile;
/**
* Using a RandomAccessFile is like using a combined DataInputStream and DataOutputStream
* (because it implements the same interfaces: DataInput and DataOutput)
* When using RandomAccessFile, you must know the layout of the file so that you can manipulate it properly.
* RandomAccessFile has specific methods to read and write primitives and UTF-8 strings.
* cannot combine it with any of the aspects of the InputStream and OutputStream subclasses
*
* @author WPeng
* @since 2012-11-5
*/
public class UsingRandomAccessFile {
static String file = "rtest.dat";
static void display() throws IOException{
RandomAccessFile rf = new RandomAccessFile(file, "r");
for(int i=0; i<7; i++){
System.out.println("Value " + i + ": " + rf.readDouble());
}
System.out.println(rf.readUTF());
rf.close();
}
public static void main(String[] args) throws IOException{
RandomAccessFile rf = new RandomAccessFile(file, "rw");
for(int i=0; i<7; i++){
rf.writeDouble(i*1.414);
}
rf.writeUTF("The end of the file");
rf.close();
display();
rf = new RandomAccessFile(file, "rw");
/**
* can use seek( ) to move about in the file and change the values.
* a double is always eight bytes long,
* to seek( ) to double number 5 you just multiply 5*8 to produce the seek value.
*/
rf.seek(5*8);
rf.writeDouble(47.0001);
rf.close();
display();
}
}
File reading & writing utilitiespackage think.in.java.io;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.TreeSet;
/**
* Static functions for reading and writing text files as a single string, and
* treating a file as an ArrayList.
* @author WPeng
*
* @since 2012-11-5
*/
public class TextFile extends ArrayList<String>{
// Read a file as a single string:
public static String read(String fileName){
StringBuilder sb = new StringBuilder();
try {
BufferedReader in = new BufferedReader(
new FileReader(
new File(fileName).getAbsoluteFile()));
try{
String s;
while((s = in.readLine()) != null){
sb.append(s);
sb.append("\n");
}
}finally{
in.close();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
return sb.toString();
}
// Write a single file in one method call:
public static void write(String fileName, String text){
try {
PrintWriter out = new PrintWriter(
new File(fileName).getAbsoluteFile());
try{
out.print(text);
}finally{
out.close();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
// Read a file, split by any regular expression:
public TextFile(String fileName, String splitter){
super(Arrays.asList(read(fileName).split(splitter)));
// Regular expression split() often leaves an empty string at the first position
if (get(0).equals("")){
remove(0);
}
}
// Normally read by lines:
public TextFile(String fileName){
this(fileName, "\n");
}
public void write(String fileName){
try {
PrintWriter out = new PrintWriter(
new File(fileName).getAbsoluteFile());
try{
for(String item : this){
out.println(item);
}
}finally{
out.close();
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* Simple test:
* @param args
*/
public static void main(String[] args) {
String file = read("TextFile.java");
write("test.txt", file);
TextFile text = new TextFile("test.txt");
text.write("test2.txt");
// Break into unique sorted list of words:
TreeSet<String> words = new TreeSet<String>(
new TextFile("TextFile.java","\\w+"));
// Display the capitalized words:
System.out.println(words.headSet("a"));
}
}
Reading & Writing binary filespackage think.in.java.io;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
/**
* Utility for reading files in binary form.
* @author WPeng
*
* @since 2012-11-6
*/
public class BinaryFile {
public static byte[] read(File bfile) throws IOException{
BufferedInputStream bf = new BufferedInputStream(
new FileInputStream(bfile));
try {
byte[] data = new byte[bf.available()];
bf.read(data);
return data;
} finally{
bf.close();
}
}
public static byte[] read(String bFile) throws IOException{
return read(new File(bFile).getAbsoluteFile());
}
public static void write(File bfile, byte[] data) throws IOException{
BufferedOutputStream bf = new BufferedOutputStream(
new FileOutputStream(bfile));
try{
bf.write(data);
}finally{
bf.close();
}
}
public static void write(String bFile, byte[] data) throws IOException{
write(new File(bFile).getAbsoluteFile(), data);
}
public static void main(String[] args) throws IOException {
byte[] data = read("123.jpg");
write("321.jpg", data);
}
}
Redirecting standard I/Opackage think.in.java.io;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
/**
* Demonstrates standard I/O redirection
* I/O redirection manipulates streams of bytes
* @author WPeng
*
* @since 2012-11-6
*/
public class Redirecting {
public static void main(String[] args) throws IOException {
/**
* This program attaches standard input to a file and redirects standard output and standard error to another file.
* */
PrintStream console = System.out;
/**
* Notice that it stores a reference to the original System.
* out object at the beginning of the program,
* and restores the system output to that object at the end.
* */
BufferedInputStream in = new BufferedInputStream(
new FileInputStream("Redirecting.java"));
PrintStream out = new PrintStream(
new BufferedOutputStream(
new FileOutputStream("test.out")));
System.setIn(in);
System.setOut(out);
System.setErr(out);
BufferedReader br = new BufferedReader(
new InputStreamReader(System.in));
String s;
while((s=br.readLine()) != null){
System.out.println(s);
}
out.close();
System.setOut(console);
}
}
Process controlexecute other operating system programs from inside Java, and to control the input and output from such programs.
package think.in.java.io;
import java.io.BufferedReader;
import java.io.InputStreamReader;
/**
* Run an operating system command and send the output to the console.
* @author WPeng
*
* @since 2012-11-6
*/
public class OSExcute {
public static void command(String command){
boolean err = false;
try {
// To capture the standard output stream from the program as it executes, you call getInputStream( ).
Process process = new ProcessBuilder(command.split(" ")).start();
BufferedReader results = new BufferedReader(
new InputStreamReader(process.getInputStream()));
String s;
while((s=results.readLine()) != null){
System.out.println(s);
}
BufferedReader errors = new BufferedReader(
new InputStreamReader(process.getErrorStream()));
// Report errors and return nonzero value to calling process if there are problems.
while((s = errors.readLine()) != null){
System.err.println(s);
err = true;
}
} catch (Exception e) {
// Compensate for window 2000, which throws an exception for the default command line.
if(!command.startsWith("CMD /C")){
command("CMD /C" +command);
}else{
throw new RuntimeException();
}
}
if(err){
throw new OSExecuteException("Errors executing " + command);
}
}
/**
* OSExcute Demo
* @param args
*/
public static void main(String[] args) {
OSExcute.command("set");
}
}