Java的输入输出流分为字节流和字符流
InputStream/Reader:所有输入流的基类,前者是字节输入流,后者是字符输入流
OutputStream/Writer:所有输出流的基类,前者是字节输出流,后者是字符输出流
FileInputStream/FileReader分别继承InputStream/Reader实现输入流操作:
字节流输入:
import java.io.FileInputStream;
import java.io.IOException;
//import java.io.File;
public class FileInputStreamTest
{
public static void main(String[] args) throws IOException {
//创建字节输入流
FileInputStream fis = new FileInputStream("F:\\Project\\HelloJava\\src\\IO\\FileInputStreamTest.java");
//创建一个长度为1024的“竹筒”
byte[] bbuf = new byte[1024];
// 用户保存实际读取的字节数
int hasRead = 0;
while((hasRead = fis.read(bbuf)) > 0) {
System.out.print(new String(bbuf, 0, hasRead) );
}
fis.close();
}
}
字符流输入:
import java.io.IOException;
import java.io.FileReader;
public class FileReaderTest {
public static void main(String[] args) throws IOException {
FileReader fr = new FileReader("F:\\Project\\HelloJava\\src\\IO\\FileReaderTest.java");
try {
char[] cbuf = new char[32];
int hasRead = 0;
while((hasRead = fr.read(cbuf) ) > 0) {
System.out.print(new String(cbuf, 0, hasRead) );
}
}
catch(IOException ex) {
ex.printStackTrace();
}
}
}
字节输出流:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileOutputStreamTest {
public static void main(String[] args) throws IOException {
//创建字节输入流
FileInputStream fis = new FileInputStream("F:\\Project\\HelloJava\\src\\IO\\FileOutputStreamTest.java");
//创建字节输出流
FileOutputStream fos = new FileOutputStream("F:\\Project\\HelloJava\\src\\IO\\new.txt");
try {
byte[] bbuf = new byte[1024];
int hasRead = 0;
while((hasRead = fis.read(bbuf) ) > 0) {
fos.write(bbuf, 0, hasRead);
}
}
catch (IOException ioe) {
ioe.printStackTrace();
}
}
}