Java IO測試範例-位元組流-字元流

來源:互聯網
上載者:User

//***

* 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");

}
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.