惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

云风的 BLOG
云风的 BLOG
Help Net Security
Help Net Security
Y
Y Combinator Blog
WordPress大学
WordPress大学
D
DataBreaches.Net
N
Netflix TechBlog - Medium
U
Unit 42
爱范儿
爱范儿
MyScale Blog
MyScale Blog
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
博客园 - 司徒正美
Google DeepMind News
Google DeepMind News
D
Docker
H
Help Net Security
Stack Overflow Blog
Stack Overflow Blog
宝玉的分享
宝玉的分享
博客园_首页
Microsoft Security Blog
Microsoft Security Blog
Engineering at Meta
Engineering at Meta
Know Your Adversary
Know Your Adversary
P
Privacy & Cybersecurity Law Blog
P
Proofpoint News Feed
T
Tenable Blog
S
Schneier on Security
V
Vulnerabilities – Threatpost
V
V2EX
T
Tor Project blog
Security Latest
Security Latest
S
Securelist
G
Google Developers Blog
NISL@THU
NISL@THU
Schneier on Security
Schneier on Security
Webroot Blog
Webroot Blog
小众软件
小众软件
Google Online Security Blog
Google Online Security Blog
阮一峰的网络日志
阮一峰的网络日志
W
WeLiveSecurity
IT之家
IT之家
I
InfoQ
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
月光博客
月光博客
I
Intezer
T
The Blog of Author Tim Ferriss
C
Cisco Blogs
博客园 - 【当耐特】
The GitHub Blog
The GitHub Blog
Cloudbric
Cloudbric
Scott Helme
Scott Helme
The Cloudflare Blog
L
LINUX DO - 热门话题

博客园 - 马森

java中的io系统详解 MongoDB资料汇总 字符编码笔记:ASCII,Unicode和UTF-8 jQuery和ExtJS的timeOut超时设置和event事件处理 Sybase字符串函数-数学函数-系统函数 inux 设置系统时间和硬件时间 Sybase采用固定表+存储过程实现分页 Wordpress XML-RPC协议说明 struts2 action 配置方法 &&struts2的配置文件 理解 SET CHAINED command not allowed within multi-statement transaction. sybase性能优化 - 马森 - 博客园 Java引用对象SoftReference WeakReference PhantomReference(二) [整理]centos下配置和安装 jstl字符串处理 [原]动态打jar包程序,可用于手机图片音乐游戏的动态打包 Java,Tomcat,Mysql乱码总结 [原]output parameters have not yet been processed源自返回了多个数据集 [转]MS SQL Server数据库事务锁机制分析 tomcat支持ssl时Keystore was tampered with, or password was incorrect
Java IO测试样例-字节流-字符流
马森 · 2012-07-06 · via 博客园 - 马森

//***

* java中的IO详解见 http://www.senma.org/blogs/356.html

* 也可以参考:http://www.cnblogs.com/rollenholt/archive/2011/09/11/2173787.html

*/

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.io.PrintStream;
import java.io.SequenceInputStream;
import java.net.URL;
import java.net.URLConnection;
/****
*
* @author masen
* http://weibo.com/masen
* http://www.senma.org/
*
*/
public class ReadFileTest {

/***
* 字符流读取文本
* @throws IOException
*/
public static void readerReadFile(String filename)
{
//BufferedReader reader=new BufferedReader(new FileReader(name));
//因为Filereader继承InputStreamReader 故两种写法都是ok的
BufferedReader reader=null;
try {
reader = new BufferedReader(new InputStreamReader(new FileInputStream(filename)));
String s1="";
while((s1=reader.readLine())!=null)
{
System.out.println(s1);
}

} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally
{
try {
if(reader!=null)reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

/***
* 字节流读取文本
* 字节流读取web信息,同理
* @throws IOException
*/
public static void streamReadFile(String filename)
{
FileInputStream stream=null;
try {
stream=new FileInputStream(filename);
byte[] temp=new byte[1024];
int len=0;
while((len=stream.read(temp))!=-1)
{//注意因为temp缓存是固定字节长,不能全部output
System.out.print(new String(temp,0,len));
}

} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally
{
try {
if(stream!=null)stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

/***
* 网络读取数据,使用字符流
* 这里可以明显看到InputstreamReader是 stream到reader的桥梁
* @param url
*/
public static void readerReadWeb(String url)
{
BufferedReader reader=null;
try {
URLConnection con=new URL(url).openConnection();
reader=new BufferedReader(new InputStreamReader(con.getInputStream()));
String s1="";
while((s1=reader.readLine())!=null)
{
System.out.println(s1);
}

} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally
{
try {
if(reader!=null)reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

/***
* 递归罗列目录
*
* @param dir 当前文件目录
* @param name 当前文件名
* @param deep 当前递归深度
* @param dept 允许的最大深度
*/
public static void listDir(String dir,String name,int deep,int dept)
{
File f=new File(dir+File.separator+name);
for(int i=0;i<deep;i++)
System.out.print(" ");
if(f.isDirectory())
{
String[] dirs=f.list();
System.out.print("--"+name);

if(dirs==null||dirs.length==0)
{
return;
}
System.out.print("\r\n");
for(String s:dirs)
{
if((deep+1)<dept)
listDir(dir+File.separator,s,deep+1,dept);
}
}
else
{
System.out.print("--"+name);
System.out.print("\r\n");
}

}

/***
* 字节流写入文件
* @param file
* @param content
*/
public static void streamWriteFile(String name,String content)
{
File f=new File(name);
FileOutputStream stream=null;
try {
if(!f.exists())
{//文件不存在
f.createNewFile();
stream=new FileOutputStream(f);
byte[] temp=content.getBytes();
stream.write(temp);
}
else
{//文件存在则追加
stream=new FileOutputStream(f,true);
byte[] temp=content.getBytes();
for(int i=0;i<temp.length;i++)
stream.write(temp[i]);
}

} catch (IOException e) {
e.printStackTrace();
}
finally
{
try {
if(stream!=null)
stream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

/***
* 字符流写入文件
* @param file
* @param content
*/
public static void writerWriteFile(String name,String content)
{
File f=new File(name);
FileWriter stream=null;
try {
if(!f.exists())
{//文件不存在
f.createNewFile();
stream=new FileWriter(f);
stream.write(content);
}
else
{//文件存在则追加
stream=new FileWriter(f,true);
stream.write(content);
}

} catch (IOException e) {
e.printStackTrace();
}
finally
{
try {
if(stream!=null)
stream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

/***
* 管道字节流测试
* 字符流测试类似
*
*/
public class PipeWriter implements Runnable
{
private PipedOutputStream out = null;
private String content;
public PipeWriter()
{
out=new PipedOutputStream();
}

public PipedOutputStream getOut() {
return out;
}

public String getContent() {
return content;
}

public void setContent(String content) {
this.content = content;
}

public void run() {
while(content!=null&&!content.equals(""))
{
try {
out.write(content.getBytes());
content="";
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}

}

public class PipeReader implements Runnable
{
private PipedInputStream in = null;
public PipeReader()
{
in=new PipedInputStream();
}

public void run() {
byte[] buf = new byte[1024];
try {
int len = in.read(buf);
System.out.println(new String(buf,0,len));
//in.close();
} catch (IOException e) {
e.printStackTrace();
}
}

public PipedInputStream getIn() {
return in;
}


}

/***
* printstream测试
* 可见printstream不直接针对具体的输出流形态
* 对比同类型的FileOutputStream 它更抽象化,相当于写操作的封装接口:把写的内容交给输出流,具体实现完全不管。
*
* System.out可以重定向为对应的stream流
* 同理System.in也可以如此。不再举例。
*/
public static void printStreamTest()
{
PrintStream print=null;
try {
print = new PrintStream(new FileOutputStream(new File("d:"
+ File.separator + "hello.txt"),true));
print.println("我喜欢你");
print.printf("姓名:%s. 年龄:%d.","杨幂",15);
print.close();
print=new PrintStream(System.out);
print.println("我喜欢你");
print.printf("姓名:%s. 年龄:%d.","杨幂",15);
print.close();

//重定向系统输出流,例如log4j
print = new PrintStream(new FileOutputStream(new File("d:"
+ File.separator + "hello.txt"),true));
System.setOut(print);
System.out.println("打死你");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

/****
* sequenceinputstream测试,将两个input流按照先后顺序合并。
* @param name1
* @param name2
*/
public static void sequenceInput(String name1,String name2)
{
try {
InputStream a=new FileInputStream(name1);
InputStream b=new FileInputStream(name2);
SequenceInputStream s=new SequenceInputStream(a,b);
BufferedReader r=new BufferedReader(new InputStreamReader(s));
String t="";
while((t=r.readLine())!=null)
{
System.out.println(t);
}
a.close();
b.close();
s.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

/**
* @param args
*/
public static void main(String[] args) {
//streamReadFile("c:/t1.txt");
//readerReadFile("c:/t1.txt");
//listDir("d:","",0,4);
//streamWriteFile("d:/1.txt","杨幂");
//streamWriteFile("d:/1.txt","刘恺威");
//writerWriteFile("d:/2.txt","杨幂");
//writerWriteFile("d:/2.txt","刘恺威");

/***
ReadFileTest t=new ReadFileTest();
PipeWriter x=t.new PipeWriter();
PipeReader y=t.new PipeReader();
Thread w=new Thread(x);
Thread r=new Thread(y);
try {
x.getOut().connect(y.getIn());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
x.setContent("111");
w.start();
r.start();
x.setContent("111");
**/

///printStreamTest();

sequenceInput("d:/1.txt","d:/2.txt");

}
}