Java IO系统

Java IO系统

File类

File类既能代表一个特定文件的名称,又能代表一个目录下的一组文件的名称;还能用来创建新的目录或尚不存在的完整路径。当然,File 也允许我们查看文件的特性(如大小、最后修改日期、读/写),检查某个 File 对象代表的是一个文件还是一个目录,并可以删除文件。

下面这段代码通过 File 的 list 操作实现了指定路径的遍历;同时通过指定目录过滤器,实现了对文件或文件夹的筛选;并利用 Array.sort() 方法实现了对结果字符串数组的排序。而且 FilenameFilter 使用了匿名内部类(当然也可以使用 lambda 表达式),需要注意的是内部类所要使用的数据,在外部类中必须定义为 final 的才可以使用。


import java.util.regex.*;
import java.io.*;
import java.util.*;

public class DirList{
	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);
	}
} /* Output
DirList$1.class
DirList.class
DirList.java
*///:~

Java Platform SE中的方法介绍

Modifier and TypeMethod and Description
booleancanExecute()

Tests whether the application can execute the file denoted by this abstract pathname.

booleancanRead()

Tests whether the application can read the file denoted by this abstract pathname.

booleancanWrite()

Tests whether the application can modify the file denoted by this abstract pathname.

intcompareTo(File pathname)

Compares two abstract pathnames lexicographically.

booleancreateNewFile()

Atomically creates a new, empty file named by this abstract pathname if and only if a file with this name does not yet exist.

static FilecreateTempFile(String prefix, String suffix)

Creates an empty file in the default temporary-file directory, using the given prefix and suffix to generate its name.

static FilecreateTempFile(String prefix, String suffix, File directory)

Creates a new empty file in the specified directory, using the given prefix and suffix strings to generate its name.

booleandelete()

Deletes the file or directory denoted by this abstract pathname.

voiddeleteOnExit()

Requests that the file or directory denoted by this abstract pathname be deleted when the virtual machine terminates.

booleanequals(Object obj)

Tests this abstract pathname for equality with the given object.

booleanexists()

Tests whether the file or directory denoted by this abstract pathname exists.

FilegetAbsoluteFile()

Returns the absolute form of this abstract pathname.

StringgetAbsolutePath()

Returns the absolute pathname string of this abstract pathname.

FilegetCanonicalFile()

Returns the canonical form of this abstract pathname.

StringgetCanonicalPath()

Returns the canonical pathname string of this abstract pathname.

longgetFreeSpace()

Returns the number of unallocated bytes in the partition named by this abstract path name.

StringgetName()

Returns the name of the file or directory denoted by this abstract pathname.

StringgetParent()

Returns the pathname string of this abstract pathname's parent, or null if this pathname does not name a parent directory.

FilegetParentFile()

Returns the abstract pathname of this abstract pathname's parent, or null if this pathname does not name a parent directory.

StringgetPath()

Converts this abstract pathname into a pathname string.

longgetTotalSpace()

Returns the size of the partition named by this abstract pathname.

longgetUsableSpace()

Returns the number of bytes available to this virtual machine on the partition named by this abstract pathname.

inthashCode()

Computes a hash code for this abstract pathname.

booleanisAbsolute()

Tests whether this abstract pathname is absolute.

booleanisDirectory()

Tests whether the file denoted by this abstract pathname is a directory.

booleanisFile()

Tests whether the file denoted by this abstract pathname is a normal file.

booleanisHidden()

Tests whether the file named by this abstract pathname is a hidden file.

longlastModified()

Returns the time that the file denoted by this abstract pathname was last modified.

longlength()

Returns the length of the file denoted by this abstract pathname.

String[]list()

Returns an array of strings naming the files and directories in the directory denoted by this abstract pathname.

String[]list(FilenameFilter filter)

Returns an array of strings naming the files and directories in the directory denoted by this abstract pathname that satisfy the specified filter.

File[]listFiles()

Returns an array of abstract pathnames denoting the files in the directory denoted by this abstract pathname.

File[]listFiles(FileFilter filter)

Returns an array of abstract pathnames denoting the files and directories in the directory denoted by this abstract pathname that satisfy the specified filter.

File[]listFiles(FilenameFilter filter)

Returns an array of abstract pathnames denoting the files and directories in the directory denoted by this abstract pathname that satisfy the specified filter.

static File[]listRoots()

List the available filesystem roots.

booleanmkdir()

Creates the directory named by this abstract pathname.

booleanmkdirs()

Creates the directory named by this abstract pathname, including any necessary but nonexistent parent directories.

booleanrenameTo(File dest)

Renames the file denoted by this abstract pathname.

booleansetExecutable(boolean executable)

A convenience method to set the owner's execute permission for this abstract pathname.

booleansetExecutable(boolean executable, boolean ownerOnly)

Sets the owner's or everybody's execute permission for this abstract pathname.

booleansetLastModified(long time)

Sets the last-modified time of the file or directory named by this abstract pathname.

booleansetReadable(boolean readable)

A convenience method to set the owner's read permission for this abstract pathname.

booleansetReadable(boolean readable, boolean ownerOnly)

Sets the owner's or everybody's read permission for this abstract pathname.

booleansetReadOnly()

Marks the file or directory named by this abstract pathname so that only read operations are allowed.

booleansetWritable(boolean writable)

A convenience method to set the owner's write permission for this abstract pathname.

booleansetWritable(boolean writable, boolean ownerOnly)

Sets the owner's or everybody's write permission for this abstract pathname.

PathtoPath()

Returns a java.nio.file.Path object constructed from the this abstract path.

StringtoString()

Returns the pathname string of this abstract pathname.

URItoURI()

Constructs a file: URI that represents this abstract pathname.

输入输出

流:代表了任何有能力产出数据的数据源对象或者有能力接收数据的接收端对象;流屏蔽了实际的I/O设备中处理数据的细节。

而 Java 输入输出又分为以字节操作还是以字符(Unicode)操作之分。

主要输入输出流

缓冲输入文件(BufferedReader, FileReader)


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"));
	}
}/* Output 将对应程序按行输出

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"));
        }
}
*///:~

从内存输入(StringReader)


import java.io.*;

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);
	}
}/* Output 

import java.io.*;

public class MemoryInput{
        public static void main(String[] args) throws IOException{
                StringReader in = new StringReader(BufferedInputFile.read("Memor
yInput.java"));
                int c;
                while((c = in.read()) != -1)
                        System.out.print((char)c);
        }
}
*///:~

格式化的内存输入(DataInputStream, ByteArrayInputStream)

import java.io.*;

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");
		}
	}
}/* Output 
import java.io.*;

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");
                }
        }
}
End of stream
*///:~

格式化的内存输入(DataInputStream, BufferedInputStream, FileInputStream) 

import java.io.*;

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());
	}
}/* Output 
import java.io.*;

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());
        }
*///:~

基本的文件输出(BufferedReader, StringReader, PrintWriter, BufferedWriter, FileWriter)

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)));
		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));
	}
}/* Output 
1: import java.io.*;
2:
3: public class BasicFileOutput {
4:      static String file = "BasicFileOutput.out";
5:      public static void main(String[] args) throws IOException {
6:              BufferedReader in = new BufferedReader(
7:               new StringReader(
8:                BufferedInputFile.read("BasicFileOutput.java")));
9:              PrintWriter out = new PrintWriter(
10:              new BufferedWriter(new FileWriter(file)));
11:             int lineCount = 1;
12:             String s;
13:             while((s = in.readLine()) != null)
14:                     out.println(lineCount++ + ": " + s);
15:             out.close();
16:             // Show the stored file:
17:             System.out.println(BufferedInputFile.read(file));
18:     }
19: }
*///:~

文本文件输出的快捷方式(BufferedReader, StringReader, PrintWriter)

import java.io.*;

public class FileOutputShortcut {
	static String file = "FileOutputShortcut.out";
	public static void main(String[] args) throws IOException {
		BufferedReader in = new BufferedReader(
		 new StringReader(
		  BufferedInputFile.read("FileOutputShortcut.java")));
		// 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));
	}
}/* Output 
1: import java.io.*;
2:
3: public class FileOutputShortcut {
4:      static String file = "FileOutputShortcut.out";
5:      public static void main(String[] args) throws IOException {
6:              BufferedReader in = new BufferedReader(
7:               new StringReader(
8:                BufferedInputFile.read("FileOutputShortcut.java")));
9:              // Here's the shortcut
10:             PrintWriter out = new PrintWriter(file);
11:             int lineCount = 1;
12:             String s;
13:             while((s = in.readLine()) != null)
14:                     out.println(lineCount++ + ": " + s);
15:             out.close();
16:             // Show the stored file:
17:             System.out.println(BufferedInputFile.read(file));
18:     }
19: }
*///:~

存储和恢复数据(DataOutputStream, BufferedOutputStream, FileOutputStream, DataInputStream, BufferedInputStream, FileInputStream)

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.4143);
		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());
	}
}/* Output 
3.14159
That was pi
1.4143
Square root of 2
*///:~

读写随机访问文件 (RandomAccessFile)


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();
	}
}/* Output 
Value 0: 0.0
Value 1: 1.414
Value 2: 2.828
Value 3: 4.242
Value 4: 5.656
Value 5: 7.069999999999999
Value 6: 8.484
The end of the file
Value 0: 0.0
Value 1: 1.414
Value 2: 2.828
Value 3: 4.242
Value 4: 5.656
Value 5: 47.0001
Value 6: 8.484
The end of the file
*///:~

标准I/O

按照标准I/O模型,Java 提供了 System.in、System.out、System.err,其中 System.out、System.err 都已经被事先封装为了 PrintStream 对象,但 System.in 却是一个 InputStream, 因此在使用 System.in 之前必须对其进行封装。

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
	}
}/* Output 
This is a test.
This is a test.
*///:~

当然也可以将 System.out 封装为一个 PrintWriter,不过需要将第二个参数设置为 true,以便开启自动情况功能;否则,可能将看不到任何输出。


import java.io.*;

public class ChangeSystemOut {
	public static void main(String[] args){
		PrintWriter out = new PrintWriter(System.out, true);
		out.println("Hello, world");
	}
}/* Output 
Hello, world
*///:~

标准I/O重定向

通过 System 下的 setIn, setOut, setErr 三个函数实现标准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")));
		// set System.in
		System.setIn(in);
		// set System.out
		System.setOut(out);
		// set System.err
		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!
		// restore System.out
		System.setOut(console);
	}
}/* Output in test.out
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")));
		// set System.in
		System.setIn(in);
		// set System.out
		System.setOut(out);
		// set System.err
		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!
		// restore System.out
		System.setOut(console);
	}
}
*///:~

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值