流的定义:以程序为主,进程序为输入流,出去为输出流
使用输入流包括4个基本步骤:
1.设定输入流的源
2.创建指向源的输入流
3.让输入流读取源中的数据
4.关闭输入流
FileInputStream类(java.io)继承至InputStream类 1.创建指向文件的输入流
FileInputStream(String name)//name为文件名
FileInputStream(File file)//file指定的文件
字节输入流读取源中的数据:
int read()
int read(byte b[])
int read(byte b[],int off,int len)
关闭流:
close()
实例:
public static void main(String[] args) {
File file = new File("D:\\","测试目录\\test.txt");
int n = -1;
byte[] data = new byte[1024];
try {
InputStream inputStream = new FileInputStream(file);//创建指向源的输入流
while ((n=inputStream.read(data,0,1024))!=-1){
String s = new String(data,0,n,"GBK");//字符编码解决中文乱码
System.out.println(s);
}
inputStream.close();//关闭流
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
2.字节输出流
使用输出流包括4个基本步骤:
1.设定输出流的目的地
2.创建指向目的地的输出流
3.让输出流把数据写入到目的地
4.关闭输出流
FileOutputStream类(java.io)继承至OutputStream类 1.创建指向目的地的输出流(具有刷新功能,也就是覆盖原文件)
FileOutputStream(String name)//name为文件名
FileOutputStream(File file)//file指定的文件
2.创建指向目的地的输出流(不具有刷新功能,就是从文末写入数据)
FileOutputStream(String name,boolean append)
FileOutputStream(File file,boolean append)
字节输出流写数据
void write(int n)
void write(byte b[])
void write(byte b[],int off,int len)
关闭流:
close()
实例:
byte[] b = new byte[0];
try {
b = "我是新追加的".getBytes("GBK");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
try {
FileOutputStream outputStream = new FileOutputStream(file,true);//不具有刷新功能的输出流
outputStream.write(b,0,b.length);
outputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
输入流:父类为Reader
FileReader(String filename)
FileReader(File filename)
输出流:父类为Writer
FileWriter(String filename)
FileWriter(File filename)
BufferedReader和BufferedWriter 解决了读取一行数据的问题 构造方法:
BufferedReader(Reader in);
BufferedWriter(Writer out);
读取行的方法为readLine() 写入一个换行符的方法newLine()
实例:
try {
BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
String s = null;
try {
while ((s=bufferedReader.readLine())!=null){
StringTokenizer stringTokenizer = new StringTokenizer(s);//在java.util下,建议使用String的split()
int count = stringTokenizer.countTokens();
System.out.println("单词个数:"+count);
}
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
评论