java中的IO处理和使用,API详细介绍(二)
2017-06-07 12:46
483 查看
字符流
【向文件中写入数据】现在我们使用字符流
/**
* 字符流
* 写入数据
* */
import java.io.*;
class hello{
public static void main(String[] args) throws IOException {
String fileName="D:"+File.separator+"hello.txt";
File f=new File(fileName);
Writer out =new FileWriter(f);
String str="hello";
out.write(str);
out.close();
}
}
当你打开hello。txt的时候,会看到hello
其实这个例子上之前的例子没什么区别,只是你可以直接输入字符串,而不需要你将字符串转化为字节数组。
当你如果想问文件中追加内容的时候,可以使用将上面的声明out的哪一行换为:
Writer out =new FileWriter(f,true);
这样,当你运行程序的时候,会发现文件内容变为:
hellohello如果想在文件中换行的话,需要使用“\r\n”
比如将str变为String str="\r\nhello";
这样文件追加的str的内容就会换行了。
从文件中读内容:
/** * 字符流 * 从文件中读出内容 * */ import java.io.*; class hello{ public static void main(String[] args) throws IOException { String fileName="D:"+File.separator+"hello.txt"; File f=new File(fileName); char[] ch=new char[100]; Reader read=new FileReader(f); int count=read.read(ch); read.close(); System.out.println("读入的长度为:"+count); System.out.println("内容为"+new String(ch,0,count)); } }
【运行结果】:
读入的长度为:17
内容为hellohello
hello
当然最好采用循环读取的方式,因为我们有时候不知道文件到底有多大。
/**
* 字符流
* 从文件中读出内容
* */
import java.io.*;
class hello{
public static void main(String[] args) throws IOException {
String fileName="D:"+File.separator+"hello.txt";
File f=new File(fileName);
char[] ch=new char[100];
Reader read=new FileReader(f);
int temp=0;
int count=0;
while((temp=read.read())!=(-1)){
ch[count++]=(char)temp;
}
read.close();
System.out.println("内容为"+new String(ch,0,count));
}
}
运行结果:
内容为hellohello
hello
关于字节流和字符流的区别
实际上字节流在操作的时候本身是不会用到缓冲区的,是文件本身的直接操作的,但是字符流在操作的时候下后是会用到缓冲区的,是通过缓冲区来操作文件的。读者可以试着将上面的字节流和字符流的程序的最后一行关闭文件的代码注释掉,然后运行程序看看。你就会发现使用字节流的话,文件中已经存在内容,但是使用字符流的时候,文件中还是没有内容的,这个时候就要刷新缓冲区。
使用字节流好还是字符流好呢?
答案是字节流。首先因为硬盘上的所有文件都是以字节的形式进行传输或者保存的,包括图片等内容。但是字符只是在内存中才会形成的,所以在开发中,字节流使用广泛。文件的复制
其实DOS下就有一个文件复制功能,比如我们想把d盘下面的hello.txt文件复制到d盘下面的rollen.txt文件中,那么我们就可以使用下面的命令:copy d:\hello.txt d:\rollen.txt
运行之后你会在d盘中看见hello.txt.,并且两个文件的内容是一样的,(这是屁话)
下面我们使用程序来复制文件吧。
基本思路还是从一个文件中读入内容,边读边写入另一个文件,就是这么简单。、
首先编写下面的代码:
/** * 文件的复制 * */ import java.io.*; class hello{ public static void main(String[] args) throws IOException { if(args.length!=2){ System.out.println("命令行参数输入有误,请检查"); System.exit(1); } File file1=new File(args[0]); File file2=new File(args[1]); if(!file1.exists()){ System.out.println("被复制的文件不存在"); System.exit(1); } InputStream input=new FileInputStream(file1); OutputStream output=new FileOutputStream(file2); if((input!=null)&&(output!=null)){ int temp=0; while((temp=input.read())!=(-1)){ output.write(temp); } } input.close(); output.close(); } }
然后在命令行下面
javac hello.java
java hello d:\hello.txt d:\rollen.txt
现在你就会在d盘看到rollen。txt了,
OutputStreramWriter 和InputStreamReader类
整个IO类中除了字节流和字符流还包括字节和字符转换流。OutputStreramWriter将输出的字符流转化为字节流
InputStreamReader将输入的字节流转换为字符流
但是不管如何操作,最后都是以字节的形式保存在文件中的。
将字节输出流转化为字符输出流
/** * 将字节输出流转化为字符输出流 * */ import java.io.*; class hello{ public static void main(String[] args) throws IOException { String fileName= "d:"+File.separator+"hello.txt"; File file=new File(fileName); Writer out=new OutputStreamWriter(new FileOutputStream(file)); out.write("hello"); out.close(); } }
运行结果:文件中内容为:hello
将字节输入流变为字符输入流
/*** 将字节输入流变为字符输入流
* */
import java.io.*;
class hello{
public static void main(String[] args) throws IOException {
String fileName= "d:"+File.separator+"hello.txt";
File file=new File(fileName);
Reader read=new InputStreamReader(new FileInputStream(file));
char[] b=new char[100];
int len=read.read(b);
System.out.println(new String(b,0,len));
read.close();
}
}
【运行结果】:hello
前面列举的输出输入都是以文件进行的,现在我们以内容为输出输入目的地,使用内存操作流
ByteArrayInputStream 主要将内容写入内容
ByteArrayOutputStream 主要将内容从内存输出
使用内存操作流将一个大写字母转化为小写字母
/*** 使用内存操作流将一个大写字母转化为小写字母
* */
import java.io.*;
class hello{
public static void main(String[] args) throws IOException {
String str="ROLLENHOLT";
ByteArrayInputStream input=new ByteArrayInputStream(str.getBytes());
ByteArrayOutputStream output=new ByteArrayOutputStream();
int temp=0;
while((temp=input.read())!=-1){
char ch=(char)temp;
output.write(Character.toLowerCase(ch));
}
String outStr=output.toString();
input.close();
output.close();
System.out.println(outStr);
}
}
【运行结果】:
rollenholt
内容操作流一般使用来生成一些临时信息采用的,这样可以避免删除的麻烦。
管道流
管道流主要可以进行两个线程之间的通信。PipedOutputStream 管道输出流
PipedInputStream 管道输入流
验证管道流
/** * 验证管道流 * */ import java.io.*; /** * 消息发送类 * */ class Send implements Runnable{ private PipedOutputStream out=null; public Send() { out=new PipedOutputStream(); } public PipedOutputStream getOut(){ return this.out; } public void run(){ String message="hello , Rollen"; try{ out.write(message.getBytes()); }catch (Exception e) { e.printStackTrace(); }try{ out.close(); }catch (Exception e) { e.printStackTrace(); } } } /** * 接受消息类 * */ class Recive implements Runnable{ private PipedInputStream input=null; public Recive(){ this.input=new PipedInputStream(); } public PipedInputStream getInput(){ return this.input; } public void run(){ byte[] b=new byte[1000]; int len=0; try{ len=this.input.read(b); }catch (Exception e) { e.printStackTrace(); }try{ input.close(); }catch (Exception e) { e.printStackTrace(); } System.out.println("接受的内容为 "+(new String(b,0,len))); } } /** * 测试类 * */ class hello{ public static void main(String[] args) throws IOException { Send send=new Send(); Recive recive=new Recive(); try{ //管道连接 send.getOut().connect(recive.getInput()); }catch (Exception e) { e.printStackTrace(); } new Thread(send).start(); new Thread(recive).start(); } }
【运行结果】:
接受的内容为 hello , Rollen
打印流
/** * 使用PrintStream进行输出 * */ import java.io.*; class hello { public static void main(String[] args) throws IOException { PrintStream print = new PrintStream(new FileOutputStream(new File("d:" + File.separator + "hello.txt"))); print.println(true); print.println("Rollen"); print.close(); } }
【运行结果】:
true
Rollen
当然也可以格式化输出
/** * 使用PrintStream进行输出 * 并进行格式化 * */ import java.io.*; class hello { public static void main(String[] args) throws IOException { PrintStream print = new PrintStream(new FileOutputStream(new File("d:" + File.separator + "hello.txt"))); String name="Rollen"; int age=20; print.printf("姓名:%s. 年龄:%d.",name,age); print.close(); } }
【运行结果】:
姓名:Rollen. 年龄:20.
使用OutputStream向屏幕上输出内容
/**
* 使用OutputStream向屏幕上输出内容
* */
import java.io.*;
class hello {
public static void main(String[] args) throws IOException {
OutputStream out=System.out;
try{
out.write("hello".getBytes());
}catch (Exception e) {
e.printStackTrace();
}
try{
out.close();
}catch (Exception e) {
e.printStackTrace();
}
}
}
【运行结果】:
hello
输入输出重定向
import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.PrintStream; /** * 为System.out.println()重定向输出 * */ public class systemDemo{ public static void main(String[] args){ // 此刻直接输出到屏幕 System.out.println("hello"); File file = new File("d:" + File.separator + "hello.txt"); try{ System.setOut(new PrintStream(new FileOutputStream(file))); }catch(FileNotFoundException e){ e.printStackTrace(); } System.out.println("这些内容在文件中才能看到哦!"); } }
【运行结果】:
eclipse的控制台输出的是hello。然后当我们查看d盘下面的hello.txt文件的时候,会在里面看到:这些内容在文件中才能看到哦!
import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.PrintStream; /** * System.err重定向 这个例子也提示我们可以使用这种方法保存错误信息 * */ public class systemErr{ public static void main(String[] args){ File file = new File("d:" + File.separator + "hello.txt"); System.err.println("这些在控制台输出"); try{ System.setErr(new PrintStream(new FileOutputStream(file))); }catch(FileNotFoundException e){ e.printStackTrace(); } System.err.println("这些在文件中才能看到哦!"); } }
【运行结果】: 你会在eclipse的控制台看到红色的输出:“这些在控制台输出”,然后在d盘下面的hello.txt中会看到:这些在文件中才能看到哦!
import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; /** * System.in重定向 * */ public class systemIn{ public static void main(String[] args){ File file = new File("d:" + File.separator + "hello.txt"); if(!file.exists()){ return; }else{ try{ System.setIn(new FileInputStream(file)); }catch(FileNotFoundException e){ e.printStackTrace(); } byte[] bytes = new byte[1024]; int len = 0; try{ len = System.in.read(bytes); }catch(IOException e){ e.printStackTrace(); } System.out.println("读入的内容为:" + new String(bytes, 0, len)); } } }
BufferedReader的小例子
注意: BufferedReader只能接受字符流的缓冲区,因为每一个中文需要占据两个字节,所以需要将System.in这个字节输入流变为字符输入流,采用:<
b22f
/p>
下面给一个实例:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* 使用缓冲区从键盘上读入内容
* */
public class BufferedReaderDemo{
public static void main(String[] args){
BufferedReader buf = new BufferedReader(
new InputStreamReader(System.in));
String str = null;
System.out.println("请输入内容");
try{
str = buf.readLine();
}catch(IOException e){
e.printStackTrace();
}
System.out.println("你输入的内容是:" + str);
}
}
运行结果:
请输入内容
dasdas
你输入的内容是:dasdas
相关文章推荐
- java中的IO处理和使用,API详细介绍(一)
- Glide图片框架使用详细介绍(三)自定义glide以及图片处理自定义transform
- Java 集合系列06之 Vector详细介绍(源码解析)和使用示例
- HBase总结(十一)hbase Java API 介绍及使用示例
- 在EasyJWeb中使用Java Excel API 处理电子表格
- Java 集合系列13之 WeakHashMap详细介绍(源码解析)和使用示例
- hbase Java API 介绍及使用示例(一)
- ACM中使用JAVA的详细介绍
- Java 集合框架--HashMap详细介绍和使用总结
- 详细介绍Java语言中的IO系统(1)
- Java输入输出流的使用详细介绍
- 第八节:详细讲解Java中的异常处理情况与I/O流的介绍以及类集合框架
- ELK研究(一):elasticsearch java api接口操作ES集群 ---TransportClient的使用介绍 bulk批量提交数据
- Java IO中几个主要类介绍和使用
- JAVA之IO流(超详细的Java.io包的介绍!)
- Java 集合系列06之 Vector详细介绍(源码解析)和使用示例
- android之Looper详解及api详细介绍,使用案例
- Java【集合系列】-12- TreeMap详细介绍(源码解析)和使用示例
- Java异常处理机制的详细讲解和使用技巧
- Java 集合系列03之 ArrayList详细介绍(源码解析)和使用示例