日期:2014-05-20  浏览次数:20783 次

想了一晚上都没想明白:请高手指点;对java输入输出中,字节流与字符流是不是可以相互转化的疑问?
对java输入输出中,字节流与字符流是不是可以相互转化的疑问?
可以结合以下程序说明,其中第一个程序运行正确,第二个编译能通过,但是不能实现线程之间通讯.搞不懂是为什么?程序其实很简单,希望大家指点我一下,不胜感激!
Java code
 
//第一个程序
import java.io.*;
public class Try
{
public static void main(String args[])
{
try
{
PipedInputStream pis = new PipedInputStream(); // 构造PipedInputStream对象
PipedOutputStream pos = new PipedOutputStream();// 构造PipedOutputStream对//象
pos.connect(pis); // pos 与pis连接
new Sender(pos, "1.txt").start(); // 构造、启动发送线程
new Receiver(pis, "2.txt").start(); // 构造、启动接收线程
} catch (IOException e)
{
System.out.println("pipe error" + e);
}
}
}

class Sender extends Thread
{
PipedOutputStream pos;

File file;

Sender(PipedOutputStream pos, String file)
{
this.pos = pos;
this.file = new File(file);
}

public void run()
{
try
{
FileInputStream fs = new FileInputStream(file);
int data;
while ((data = fs.read()) != -1)
{
pos.write(data);
}
} catch (IOException e)
{
System.out.println("sender error" + e);
}
}
}

class Receiver extends Thread
{
PipedInputStream pis;

File file;

Receiver(PipedInputStream pis, String file)
{
this.pis = pis;
this.file = new File(file);
}

public void run()
{
try
{
FileOutputStream fs = new FileOutputStream(file);
int data;
while ((data = pis.read()) != -1)
{
fs.write(data);
}
pis.close();
} catch (IOException e)
{
System.out.println("receiver error" + e);
}
}
}


------------------------------------------------------------


//第二个程序
import java.io.*;

public class Shishi
{
public static void main(String args[])
{
try
{
PipedReader pis = new PipedReader(); // 构造PipedReader对象
PipedWriter pos = new PipedWriter();// 构造PipedWriter对//象
pos.connect(pis); // pos 与pis连接
new Sender(pos, "1.txt").start(); // 构造、启动发送线程
new Receiver(pis, "2.txt").start(); // 构造、启动接收线程
} catch (IOException e)
{
System.out.println("pipe error" + e);
}
}
}

class Sender extends Thread
{
PipedWriter pos;

File file;

Sender(PipedWriter pos, String file)throws IOException
{
this.pos = pos;
this.file = new File(file);
}

public void run()
{
try
{
FileReader fs = new FileReader(file);
int data;
while ((data = fs.read()) != -1)
{
pos.write(data);
}
} catch (IOException e)
{
System.out.println("sender error" + e);
}
}
}

class Receiver extends Thread
{
PipedReader pis;

File file;

Receiver(PipedReader pis, String file)throws IOException
{
this.pis = pis;
this.file = new File(file);
}

public void run()
{

try
{
FileWriter fs = new FileWriter(file);
int data;
while ((data = pis.read()) != -1)
{
fs.write(data);
}

} catch (IOException e)
{
System.out.println("receiver error" + e);