想了一晚上都没想明白:请高手指点;对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
{
PipedOutputStreampos;
Filefile;
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
{
PipedInputStreampis;
Filefile;
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
{
PipedWriterpos;
Filefile;
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
{
PipedReaderpis;
Filefile;
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);
}
}
}
[解决办法]
第二个程序没写入文件 就被异常退出 改下
public void run()
{
try
{
FileWriter fs = new FileWriter(file);
int data;
while ((data = pis.read()) != -1)
{
fs.write(data);
fs.flush();
}
} catch (IOException e)
{
System.out.println("receiver error" + e);
}
}
[解决办法]
字符流是用来读写文本的。
字节流可以用来读写所有文件,包括文本在内。
因为字节流读取的是字节,计算机里最基本的存储单位就是字节。