您的位置:首页 > 职场人生

黑马程序员——Java基础——IO流(二)

2015-11-25 19:23 801 查看
------Java培训、Android培训、iOS培训、.Net培训、期待与您交流! -------

package cn.fuxi._07io;
/**
* IO常用基类_字节流
* 读取一个键盘录入的数据,并打印在控制台上.
* 键盘本身就是一个标准的输入设备,对Java而言,对于这种输入设备都有对应的对象.
*
* P.S.
* 1.获取键盘录入数据,然后将数据流向显示器,那么显示器就是目的地.
* 通过System类的setIn,SetOut方法可以对默认设备经行改变.
* System.setIm(new FileInputStream("1.txt"));//将源改成文件1.txt.
* System.setOut(new PrintStream("2.txt"));//将目的改成文件2.txt.
* 因为是字节流处理的是文本数据,可以转换成字符流,操作更方便.
* BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
* BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
*
* 2.默认的输入和输出系统不需要关,它会随着系统的结束而消失.
*/
import java.io.*;

public class _01InputStream {
public static void main(String[] args) throws IOException{
readKey();
}
public static void readKey() throws IOException{
InputStream in = System.in;
int ch = in.read();//阻塞式方法
System.out.println(ch);//输出第一个字符的ASCII码
ch = in.read();
System.out.println(ch);//输出第二个字符的ASCII码
ch = in.read();
System.out.println(ch);//输出第三个字符的ASCII码
in.close();
}
}
输出结果:
asdads

97

115

100

package cn.fuxi._07io;
/**
* 练习:
* 		获取用户键盘录入的数据,并将数据变成大写显示在控制台上,如果用户输入over,结束键盘录入.
*
* 思路:
* 		1.因为键盘录入只读取一个字节,要判断是否over,需要将读取到的字节拼接成字符串.
* 		2.那就需要一个容器:StringBuilder.
* 		3.在用户回车之前将输入的数据变成字符串判断即可.
*/
import java.io.*;

public class _02InputStreamTest {
public static void main(String[] args) throws IOException {
//method_1();
method_2();

}
//自己修改后
public static void method_2() throws IOException{
InputStream is = System.in;//创建系统输入容器
StringBuilder stb = new StringBuilder();//创建字符接收容器
int ch = 0;
while((ch=is.read())!=-1){//将字符读取到容器中
if(ch == '\r'){//回车键的ASCII字符为'\r\n',其中'\r'不被windows识别,不起作用
continue;
}else if(ch != '\n'){//'\n'起回车作用,这里是说不敲回车时,存入字符进容器中
stb.append((char)ch);
} else {
String s = stb.toString().toUpperCase();//方便打印的字符串大写转换
if(s.equals("OVER")){//如果匹配到"over"就退出循环结束程序
break;
}
System.out.println(s);//放在后面的目的是避免吧"OVER"也打印出来
stb.delete(0, stb.length());//每一行的数据清空一次,避免重复打印
}
}
}
//教程中的方式不好理解
public static void method_1() throws IOException {
//1.创建容器
StringBuilder stb = new StringBuilder();
//2.获取键盘读取流
InputStream is = System.in;
//3.定义变量记录读取到的字节,并循环获取
int ch=0;
while((ch=is.read())!=-1){
//在存储之前需要判断是否是换行标记,因为换行标记不存储.
if(ch=='\r'){
continue;
}else if(ch == '\n'){
String temp = stb.toString();
if("over".equals(temp)){
break;
}
System.out.println(temp.toUpperCase());
stb.delete(0, stb.length());
}else{
//将读取到的字节存储到StringBuilder中
stb.append((char)ch);
}
}
}
}
输出结果:
123

123

wqwe

WQWE

rewr

REWR

over

package cn.fuxi._07io;
/**
* 转换流
* 由来:
* 		字符流与字节流之间的桥梁
* 		方便了字符流与字节流之间的操作
*
* 转换流的应用:
* 		字节流中的数据都是字符时,转换成字符流操作效率更高
*
* 转换流:
* 		InputStreamReader:字节到字符的桥梁--解码
* 		OutputaStreamWriter:字符到字节的桥梁--编码
*
* P.S.
* 		使用字节流读取一个中文字符需要读取两次,因为一个中文字符由两个字节组成,而使用字符
* 流只需要读取一次.
* 		System.out的类型时PrintStream,属于OutputStream类别.
*/
import java.io.*;
public class _03TransformStreamDemo {
public static void main(String[] args) throws IOException {
//method_Reader();
//method_ReaderAndWriter();
method_RAW();
}
//简化写法
public static void method_RAW() throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
String line = null;
while((line = br.readLine())!=null){
if(line.equalsIgnoreCase("over")){
break;
}
bw.write(line.toUpperCase()+"\r\n");
bw.flush();
}
}
//基本写法
public static void method_ReaderAndWriter() throws IOException{
InputStream is = System.in;
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
OutputStream os = System.out;
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
String line = null;
while((line=br.readLine())!=null){
if("over".equalsIgnoreCase(line)){
break;
}
bw.write(line.toUpperCase());
bw.newLine();
bw.flush();
}
bw.close();
br.close();
}

public static void method_Reader() throws IOException {
//字节流
InputStream in = System.in;
//将字节流转换成字符的桥梁,转换流
InputStreamReader isr = new InputStreamReader(in);
//对字符流经行高效装饰,缓冲区
BufferedReader br = new BufferedReader(isr);
String line = null;
while((line = br.readLine())!=null){
System.out.println(line.toUpperCase());
}
br.close();
}
}
输出结果:
123

123

asda

ASDA

ds

DS

over

package cn.fuxi._07io;
/**
* 需求:将键盘录入的数据写入到一个文件中
*
* 思路:	1.BufferedReader读取
* 		2.FileWriter写入
*/
import java.io.*;
public class _04InputStreamTest2 {
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
FileWriter fw = new FileWriter("不明觉厉.txt");
BufferedWriter bw = new BufferedWriter(fw);
String line = null;
while((line =br.readLine())!=null){
if(line.equalsIgnoreCase("over")){
break;
};
bw.write(line);
bw.newLine();
bw.flush();
}
}
}
输出结果:
sadassda

skajda

kjlasd

你好啊~!!over

over



package cn.fuxi._07io;
/**
* 需求:将一个文本文件内容输出到控制台上.
*/
import java.io.*;
public class _05OutputStreamTest {
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("不明觉厉.txt")));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
String line = null;
while((line = br.readLine())!=null){
bw.write(line);
bw.newLine();
bw.flush();
}
}
}
输出结果:
sadassda

skajda

kjlasd

你好啊~!!over

package cn.fuxi._07io;
/**
* 将一个文本文件复制到另一个文本文件中
*/
import java.io.*;
public class _06InOutPutStreamTest {
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("不明觉厉.txt")));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("Copy不明觉厉.txt")));
String line = null;
while((line = br.readLine())!=null){
bw.write(line);
bw.newLine();
bw.flush();
}
}
}
输出结果:



package cn.fuxi._07io;
/**
* 流的操作规律
*
* 之所以要弄清楚这个规律,是因为流对象太多,开发时不知道用哪个对象合适.
* 想要知道对象的开发时用到哪些对象,只要通过四个明确即可.
*
* 1.明确源和目的
* 源:	InputStream		Reader
* 目的:	OutputStream	Writer
*
* 2.明确数据是否是纯文本数据
* 源:	是纯文本:Reader
* 		不是纯文本:InputStream
* 目的:	是存文本:Writer
* 		不是纯文本:OutputStream
* 这样就可以明确需求中具体需要使用哪个体系.
*
* 3.明确具体的设备
* 源设备:
*		硬盘:File
* 		键盘:System.in
* 		内存:数组
* 		网络:Socket流
* 目的设备:
* 		硬盘:File
* 		控制台:System.out
* 		内存:数组
* 		网络:Socket流
*
* 4.是否需要额外功能
* 是否需要高效(缓冲区):
* 		需要:加上Buffered
* 		不需要:不加
*
* ==========================================================
*
* 举例:
*
* 需求1:
* 		复制一个文本文件
*
* 1.明确源和目的.
* 	源:		InputStream 	Read
* 	目的:	OutputStream 	Writer
*
* 2.是否是纯文本?
* 是!
* 源:	Reader
* 目的:	Writer
*
* 3.明确具体设备.
* 源:
* 		硬盘:File
* 目的:
* 		硬盘:File
* FileReader fr = new FileReader("a.txt");
* FileWriter fw = new FileReader("b.txt");
*
* 4.需要额外功能吗?
* 需要,高效
* BufferedReader br = new BufferedReader(fr);
* BufferedWriter bw = new BufferedWriter(fw);
*
* ============================================================
*
* 需求2:
* 		读取键盘录入信息,并写入到一个文件中.
*
* 1.明确源和目的.
* 源:	InputStream 	Reader
* 目的: OutputStream 	Writer
*
* 2.是否是纯文本?
* 是!
* 源:	Reader
* 目的:	Writer
*
* 3.明确具体设备.
* 源:
* 	键盘:System.in
* 目的:
* 	硬盘:File
* InputStream is = System.in;
* FileWriter fw = new FileWriter("b.txt");
*
* 4.需要额外的功能吗?
* 需要,转换.将字节流转换成字符流,应为明确源是Reader,这样操作文本数据更便捷.
* InputStreamReader isr = new InputStreamReader(is);
* FileWriter fw = new FileWriter("b.txt");
* 还需要功能吗?需要~高效!
* BufferedReader bf = new BufferedReader(isr);
* BufferedWriter bw = new BufferedWriter(fw);
*
* ==========================================================
*
* 需求3:
* 		将一个文本文件显示在控制台上
*
* 1.明确源和目的
* 	源:		InputStream		Reader
* 	目的:	OutputStream	Writer
*
* 2.是否是纯文本?
* 是!
* 源:	Reader
* 目的	Writer
*
* 3.明确具体设备.
* 源:
* 		硬盘:File
* 目的:
* 		控制台:System.out
* FileReader fr = new FileReader("a.txt");
* OutputStream os = System.out;
*
* 4.需要额外的功能吗?
* 需要~转换~
* FileReader fr = new FileReader("a.txt");
* OutputStreamWriter osw = new OutputStreamWriter(os);
* 需要~高效~
* BufferedReader br = new BufferedReader(fr);
* BufferedWriter bw = new BufferedWriter(osw);
*
* ==========================================================
*
* 需求4:
* 		读取键盘录入数据,显示在控制台上
*
* 1.明确源和目的
* 源:	InputStream		Reader
* 目的:	OutputStream	Writer
*
* 2.是否是纯文本?
* 是!
* 源:	Reader
* 目的:	Writer
*
* 3.明确具体设备
* 源:
* 		键盘:	System.in
* 目的:
* 		控制台:	System.out
* InputStream is = System.in;
* OutputStream os = System.out;
*
* 4.明确额外功能
* 需要~转换~
* InputStreamReader isr = new InputStreamReader(is);
* OutputStreamWriter osw = new OutputStreamWriter(os);
* 需要~缓冲高效~
* BufferedReader br = new BufferedReader(isr);
* BuffeedrWriter bw = new BufferedWriter(osw);
*/

package cn.fuxi._07io;
/**
* 练习:
* 		将一个中文字符串数据按照指定的编码表写入到一个文本文件中.
* 1.目的:OutputStream,Writer
* 2.是纯文本:Writer
* 3.设备:硬盘File
* FileWriter fw = new FileWriter("哒哒哒.txt");
* fw.write("你好~");
*
* P.S.
* FileWriter是用来写入字符文件的便捷类,此类的构造方法假定默认字符编码
* 和默认字节缓冲区大小都是可接收的.
* =============================================================
* 任何Java识别的字符数据使用的都是Unicode码表,但是FileWriter写入本地
* 文件使用的是本地编码,也就是GBK码表.
* 而OutputStreamWriter可使用指定的编码将要写入流中的字符编码成字节.
*
* P.S.
* UTF-8编码,一个中文三个字节.
* =============================================================
* 需求:打印d.txt文件中的内容至控制台显示.
* 原因分析:由于源文件中是UTF-8编码的"您好",6个字节.
* 使用FileReader类是用GBK编码进行读取,6个字节代表3个字符,并且按照GBK进行编码
* 因此才出现以上结果.
* =============================================================
* 需求:打印之前的文字的内容到控制台显示.
* 原因分析:由于c.txt文件中是GBK编码的"您好",4个字节.
* 使用InputStreamReader类是用UTF-8编码经行读取,由于GBK编码的字节使用UTF-8
* 没有对应字符,因此用"?"进行代替.
* =============================================================
* 需求:按照指定编码写字符到指定文件中.
* 如过需求中已经明确指定了编码表.那就不可以使用FileWriter,应为FileWriter内
* 部使用的默认的本地编码表.只能使用其父类,OutputStreamWriter.
* 		OutputStreamWriter接收一个字节流输出对象,既然是操作文件,那么对象应该是
* FileOutputStream.
* 		OutputStreamWriter osw = new OutputStreamWriter(new
* FileOutputStream("xx.txt"),charsetName);
* 并且需要高效:
* 		BufferedWriter bw = new BufferedWriter(osw);
* =============================================================
* 什么时候使用转换流呢?
* 1.源或者目的对应的设备是字节流,但是操作的却是文本数据,可以使用转换作为桥梁,提高
* 对文本操作的便捷.
* 2.一旦操作文本涉及到具体的指定编码表时,必须使用转换流.
* =====================================================================
* 字符流继承体系简表
* 					|--BufferedReader
*		|-->Reader	|
* 		|			|--InputStreamReader	---	FileReader
* 字符流	|
* 		|			|--BufferedWriter
* 		|-->Writer	|
* 					|--OutputStreamWriter	---	FileWriter
* =====================================================================
* 字节流继承体系简表
* 						|--FileInputStream
*		|-->InputStream	|
* 		|				|--FilterInputStream	---	BufferedInputStream
* 字节流	|
* 		|				|--Writer
* 		|-->OutoutStream|
* 						|--FilterOutputStream	---	BufferedOutputStream
* =====================================================================
*/
import java.io.*;
public class _08TransformStreamTest {
public static void main(String[] args) throws IOException {
writeText();
ReadText();
ReadText2();
}
public static void writeText() throws IOException{
FileWriter fw = new FileWriter("哒哒哒.txt");
fw.write("你好");
fw.flush();
fw.close();
}
public static void ReadText() throws IOException{
FileReader fr = new FileReader("哒哒哒.txt");
char[] buf = new char[10];
int len = fr.read(buf);
String s = new String(buf,0,len);
System.out.println(s);
fr.close();
}
public static void ReadText2()throws IOException{
InputStreamReader isr = new InputStreamReader(new FileInputStream("哒哒哒.txt"),"UTF-8");//或者Unicode
char[] buf = new char[10];
int len = isr.read(buf);
String s = new String(buf,0,len);
System.out.println(s);
isr.close();
}
}
输出结果:
你好

??



package cn.fuxi._07io;

/**
* File类
* File类用来将文件或者文件夹封装成对象,方便对文件与文件夹的属性信息进行操作.
* File对象可以作为参数传递给流的构造函数.
*
* P.S.
* 流只能操作数据,不能操作文件.
*
*/
//读一个文件,打印出来,在每一行前后加括号
import java.io.*;

public class _09FileDemo {
public static void main(String[] args) throws IOException {
constructorDemo();
}
public static void constructorDemo(){
//可以将一个已存在的,或者不存在的文件或者目录封装成file对象
//方式一
File f1 = new File("D:\\develop\\workspace\\fuxi4\\不明觉历1.txt");
//方式二
File f2 = new File("D:\\develop\\workspace\\fuxi4","不明觉历1.txt");
//方式三
File f = new File("D:\\develop\\workspace\\fuxi4");
File f3 = new File(f,"a.txt");
//考虑到Windows和Linux系统通用
File f4 = new File("d:"+File.separator+"develop"+File.separator+
"workspace"+File.separator+"fuxi4"+File.separator+"不明觉历1.txt");
//File.separator是与系统有关的默认名称分隔符.在UNIX系统上,此字段的值为'/';在Microsoft
//Windows上,它为'\\'.
}
}


package cn.fuxi._07io;
/**
* File对象的常用方法:
* 1.获取
* 	获取文件名称
* 	获取文件路径
* 	获取文件大小
* 	获取文件修改时间
*/
import java.io.*;
import java.text.DateFormat;
import java.util.*;
public class _10FileMethodDemo1 {
public static void main(String[] args) {
getDemo();
}
public static void getDemo(){
File f1 = new File("不明觉厉.txt");
File f2 = new File("D:\\develop\\workspace\\fuxi4\\不明觉厉.txt");

String name = f2.getName();
System.out.println("name: "+name);//不明觉厉.txt
String absPath = f2.getAbsolutePath();//绝对路径
System.out.println("absPath绝对路径: "+absPath);//D:\develop\workspace\fuxi4\不明觉厉.txt
String path1 = f1.getPath();
System.out.println("path1路径: "+path1);//不明觉厉.txt
String path2 = f2.getPath();
System.out.println("path2路径: "+path2);//D:\develop\workspace\fuxi4\不明觉厉.txt
long len = f2.length();
System.out.println("文件长度len: "+len);//81
long time = f2.lastModified();
System.out.println("创建时间: "+time);//1448088245611
//相对路径不同,父目录不同
//如果此路径名没有指定父目录,则放回null
String parent1 = f1.getParent();
System.out.println("父类路径parent1: "+parent1);//null
String parent2 = f2.getParent();
System.out.println("父类路径parent2: "+parent2);//D:\develop\workspace\fuxi4
Date date = new Date(time);
DateFormat df = DateFormat.getDateTimeInstance(DateFormat.LONG,DateFormat.LONG);
String s_time = df.format(date);
System.out.println("创建时间_风格: "+s_time);
}
}
输出结果:
name: 不明觉厉.txt

absPath绝对路径: D:\develop\workspace\fuxi4\不明觉厉.txt

path1路径: 不明觉厉.txt

path2路径: D:\develop\workspace\fuxi4\不明觉厉.txt

文件长度len: 41

创建时间: 1448451119615

父类路径parent1: null

父类路径parent2: D:\develop\workspace\fuxi4

创建时间_风格: 2015年11月25日 下午07时31分59秒

package cn.fuxi._07io;
/**
* 判断
*/
import java.io.*;
public class _11FileMethodDemo2 {
public static void main(String[] args) throws IOException {
isDemo();
}
public static void isDemo() throws IOException{
File f = new File("D:\\develop\\workspace\\fuxi4\\不明觉厉.txt");
boolean b = f.exists();//测试此抽象路径名表示的文件或目录是否存在.
System.out.println("此目录或路径是存在吗?"+b);//true
if(!f.exists()){
f.createNewFile();
}
//最好先判断是否存在
if(f.exists()){
System.out.println(f.isFile());//true(是文件吗?)
System.out.println(f.isDirectory());//false(是目录吗?)
}

f = new File("aa\\bb");
f.mkdirs();//创建此抽象路径名指定的目录,包括所有必需但不存在的父目录.
System.out.println(f.exists());//true
if(f.exists()){
System.out.println(f.isFile());//false
System.out.println(f.isDirectory());//true
}
}
}
输出结果:
此目录或路径是存在吗?true

true

false

true

false

true

package cn.fuxi._07io;
/**
* 重命名
*/
import java.io.*;
public class _12FileMethodDemo3 {
public static void main(String[] args) {
renameToDemo();
}
public static void renameToDemo(){
File f1 = new File("D:\\develop\\workspace\\fuxi4\\不明觉厉.txt");
File f2 = new File("D:\\develop\\workspace\\fuxi4\\不明觉厉(2).txt");
boolean b = f1.renameTo(f2);//重新命名此抽象路径名表示的文件
System.out.println(b);
}

}
输出结果:
true


package cn.fuxi._07io;
/**
* 系统根目录和容量获取
*/
import java.io.*;
public class _13FileMethodDemo4 {
public static void main(String[] args) throws IOException {
listRootsDemo();
}
public static void listRootsDemo() throws IOException{
File[] files = File.listRoots();//列出可用的文件系统根
for(File file : files){
System.out.println(file);
}
File file = new File("d:\\");
System.out.println(file.getFreeSpace());//返回此抽象路径名指定的分区中未分配的字节数。101342711808
System.out.println(file.getTotalSpace());//返回此抽象路径名指定的分区大小。107374178304
System.out.println(file.getUsableSpace());//返回此抽象路径名指定的分区上可用于此虚拟机的字节数。101342711808
}
}
输出结果:
C:\

D:\

E:\

F:\

G:\

101183361024

107374178304

101183361024

package cn.fuxi._07io;
/**
* 获取目录下的文件以及文件夹的名称
*/
import java.io.*;
public class _14FileListDemo {
public static void main(String[] args) throws IOException {
listDemo();
}
public static void listDemo() throws IOException{
File file = new File("c:\\");
//获取目录下的文件以及文件夹的名称,包含隐藏文件
//调用list方法的File对象中封装的必须是目录,否则会产生NullPointerException
//如果访问的是系统级目录也会发生空指针异常
//如果目录存在但是没有内容,会返回一个数组,但是长度为0;
String[] names = file.list();
for(String name:names){
System.out.println(name);
}
}
}
输出结果:
$360Section

$Recycle.Bin

360Rec

360SANDBOX

a

a26be26c93d927093af1c1

Alimama

Boot

bootfont.bin

bootmgr

BOOTNXT

BOOTSECT.BAK

Documents and Settings

end

hiberfil.sys

Intel

IoDemoCopyText

Linkin Park.jpg

pagefile.sys

PerfLogs

Program Files

Program Files (x86)

ProgramData

Recovery

swapfile.sys

System Volume Information

Users

Whenwhere I belong.avi

Whenwhere I be
a0de
long.txt

Windows

package cn.fuxi._07io;
/**
* 需求:获取d盘demo目录下后缀名为java的文件.
*/
import java.io.*;
public class _15FileListDemo2 {
public static void main(String[] args) throws IOException {
listDemo();
}
public static void listDemo() throws IOException{
File dir = new File("D:\\develop\\workspace\\fuxi4\\src\\cn\\fuxi\\_07io");

//String[] names = dir.list(new FilterByJava());//返回一个字符串数组,这些字符串指定此抽象路径名表示的目录中满足指定过滤器的文件和目录。
String[] names = dir.list(new SuffixFilter(".java"));
for(String name :names){
System.out.println(name);
}
}
}
class FilterByJava implements FilenameFilter{
public boolean accept(File dir,String name){
return name.endsWith(".java");
}
}
//P.S.
//由于搜索后缀为".java"便直接将".java"写死到代码中,不便于修改.
//如果要去搜索后缀为".txt"的文件又该怎么办呢?
//因此,为了提升程序的通用性,修改后的代码如下
class SuffixFilter implements FilenameFilter{
private String suffix;
public SuffixFilter(String suffix){
this.suffix = suffix;
}
public boolean accept(File dir,String name){
return name.endsWith(suffix);
}
}
输出结果:
_01InputStream.java

_02InputStreamTest.java

_03TransformStreamDemo.java

_04InputStreamTest2.java

_05OutputStreamTest.java

_06InOutPutStreamTest.java

_07IOSummary.java

_08TransformStreamTest.java

_09FileDemo.java

_10FileMethodDemo1.java

_11FileMethodDemo2.java

_12FileMethodDemo3.java

_13FileMethodDemo4.java

_14FileListDemo.java

_15FileListDemo2.java
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  黑马程序员 java io流