Java的I/O系統
阿新 • • 發佈:2018-06-02
make sage exce case info 定向 pen 接收 標準io 對象代表的是一個文件還是一個目錄,並可以刪除文件。
1.File類
File類既能代表一個特定文件的名稱,又能代表一個目錄下的一組文件的名稱。
如果我們調用不帶參數的list()
方法,便可以獲得此File對象包含的全部列表。然而,如果我們想獲得一個受限列表,例如,想得到所有擴展名為.java的文件,那麽我們就要用到“目錄過濾器”,這個類告訴我們怎樣顯示符合條件的File對象。
import java.util.regex.*;
import java.io.*;
import java.util.*;
public class DirList3 {
public static void main(final String[] args) {
File path = new File(".");
String[] list;
if(args.length == 0){
list = path.list();
}else{
list = path.list(new FilenameFilter() {
private Pattern pattern = Pattern.compile(args[0]);
public boolean accept(File dir, String name) {
return pattern.matcher(name).matches();
}
});
}
Arrays.sort(list, String.CASE_INSENSITIVE_ORDER);
for(String dirItem : list){
System.out.println(dirItem);
}
}
}
File類不僅僅只代表存在的文件或目錄。也可以用File對象來創建新的目錄或尚不存在的整個目錄路徑。我們還可以查看文件的特性(例如,大小、最後修改日期、讀/寫),檢查某個File
import java.io.*;
public class MakeDirectories {
private static void usage() {
System.err.println(
"Usage:MakeDirectories path1 ...\n" +
"Creates each path\n" +
"Usage:MakeDirectories -d path1 ...\n" +
"Deletes each path\n" +
"Usage:MakeDirectories -r path1 path2\n" +
"Renames from path1 to path2");
System.exit(1);
}
private static void fileData(File f) {
System.out.println(
"Absolute path: " + f.getAbsolutePath() +
"\n Can read: " + f.canRead() +
"\n Can write: " + f.canWrite() +
"\n getName: " + f.getName() +
"\n getParent: " + f.getParent() +
"\n getPath: " + f.getPath() +
"\n length: " + f.length() +
"\n lastModified: " + f.lastModified());
if(f.isFile()){
System.out.println("It's a file");
}else if(f.isDirectory()){
System.out.println("It's a directory");
}
}
public static void main(String[] args) {
if(args.length < 1){
usage();
}
if(args[0].equals("-r")) {
if(args.length != 3){
usage();
}
File old = new File(args[1]),rname = new File(args[2]);
old.renameTo(rname);
fileData(old);
fileData(rname);
return; // Exit main
}
int count = 0;
boolean del = false;
if(args[0].equals("-d")) {
count++;
del = true;
}
count--;
while(++count < args.length) {
File f = new File(args[count]);
if(f.exists()) {
System.out.println(f + " exists");
if(del) {
System.out.println("deleting..." + f);
f.delete();
}
}else { // Doesn't exist
if(!del) {
f.mkdirs();
System.out.println("created " + f);
}
}
fileData(f);
}
}
}
2.字節流
編程語言的I/O類庫中常使用流這個抽象概念,它代表任何有能力產出數據的數據源對象或者是有能力接收數據的接收端對象。
Java類庫中的I/O類分成輸入和輸出兩部分。
與輸入有關的所有類都應該從InputStream
繼承,而與輸出有關的所有類都應該從OutputStream
繼承。
3.字符流
Reader
和Writer
提供兼容Unicode與面向字符的I/O功能。
有時我們必須把來自於“字節”層次結構中的類和“字符”層次結構中的類結合起來使用。為了實現這個目的,要用到適配器類:InputStreamReader
可以把InputStream
轉換為Reader
,而OutputStreamWriter
可以把OututStream
轉換為Writer
。
4.I/O流的典型使用方式
4.1 緩沖輸入文件
import java.io.*;
public class BufferedInputFile {
// Throw exceptions to console:
public static String read(String filename) throws IOException {
// Reading input by lines:
BufferedReader in = new BufferedReader(new FileReader(filename));
String s;
StringBuilder sb = new StringBuilder();
while((s = in.readLine())!= null){
sb.append(s + "\n");
}
in.close();
return sb.toString();
}
public static void main(String[] args) throws IOException {
System.out.print(read("BufferedInputFile.java"));
}
}
4.2 從內存輸入
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.print((char)c);
}
}
}
4.3 格式化的內存輸入
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) {
System.err.println("End of stream");
}
}
}
public class TestEOF {
public static void main(String[] args) throws IOException {
DataInputStream in = new DataInputStream(new BufferedInputStream(new FileInputStream("TestEOF.java")));
while(in.available() != 0){
System.out.print((char)in.readByte());
}
}
}
4.4 基本的文件輸入
import java.io.*;
public class BasicFileOutput {
static String file = "BasicFileOutput.out";
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new StringReader(BufferedInputFile.read("BasicFileOutput.java")));
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(file)));
// Here's the shortcut:
//PrintWriter out = new PrintWriter(file);
int lineCount = 1;
String s;
while((s = in.readLine()) != null ){
out.println(lineCount++ + ": " + s);
}
out.close();
// Show the stored file:
System.out.println(BufferedInputFile.read(file));
}
}
4.5 存儲和恢復數據
import java.io.*;
public class StoringAndRecoveringData {
public static void main(String[] args) throws IOException {
DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream("Data.txt")));
out.writeDouble(3.14159);
out.writeUTF("That was pi");
out.writeDouble(1.41413);
out.writeUTF("Square root of 2");
out.close();
DataInputStream in = new DataInputStream(new BufferedInputStream(new FileInputStream("Data.txt")));
System.out.println(in.readDouble());
// Only readUTF() will recover the
// Java-UTF String properly:
System.out.println(in.readUTF());
System.out.println(in.readDouble());
System.out.println(in.readUTF());
}
}
4.6 讀寫隨機訪問文件
import java.io.*;
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");
rf.seek(5*8);
rf.writeDouble(47.0001);
rf.close();
display();
}
}
5標準I/O
從標準輸入中讀取
按照標準I/O模型,Java提供了System.in
、System.out
和System.err
。
import java.io.*;
public class Echo {
public static void main(String[] args) throws IOException {
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
String s;
while((s = stdin.readLine()) != null && s.length()!= 0){
System.out.println(s);
}
// An empty line or Ctrl-Z terminates the program
}
}
將System.out
轉換成PrintWriter
import java.io.*;
public class ChangeSystemOut {
public static void main(String[] args) {
PrintWriter out = new PrintWriter(System.out, true);
out.println("Hello, world");
}
}
標準I/O重定向
import java.io.*;
public class Redirecting {
public static void main(String[] args) throws IOException {
PrintStream console = System.out;
BufferedInputStream in = new BufferedInputStream(new FileInputStream("Redirecting.java"));
PrintStream out = new PrintStream(new BufferedOutputStream(new FileOutputStream("test.out")));
//setIn(InputStream)、setOut(PrintStream)和setErr(PrintStream)對標準輸入、輸出和錯誤I/O流進行重定向。
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(); // Remember this!
System.setOut(console);
}
}
Java的I/O系統