import java.io.*;
public class IOStreamDemo
{
public static void main(String[] args) throws IOException
{
// TODO 自动生成方法存根
//1.逐行读入文件“IOStreamDemo.java”
FileReader fr = new FileReader("IOStreamDemo.java");
BufferedReader in = new BufferedReader(fr);
String s1 , s2 = new String();
while ((s1 = in.readLine())!= null)
{
s2 += s1 + "/n";
}
in.close();
//2.读取标准的输入
System.out.println("Please input:");
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader stdin = new BufferedReader(isr);
System.out.println(stdin.readLine());
System.out.println("You Can See What You Input");
stdin = new BufferedReader( new InputStreamReader(System.in));
//3.从内存中读入
StringReader sr = new StringReader(s2);
int c = -1;
while ((c = sr.read()) != -1)
System.out.println((char)c);
//4.格式化的内存输入
try
{
DataInputStream dis = new DataInputStream(new ByteArrayInputStream(s2.getBytes()));
while (true)
{
System.out.print((char)dis.readByte());
}
}catch (EOFException e)
{
System.out.println("End of stream.");
}
//5.文件输出
try
{
BufferedReader bf5 = new BufferedReader(new StringReader(s2));
int lineNo = 0;
PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter("IODemo.out")));
String st;
while ((st = bf5.readLine()) != null )
pw.println(++lineNo + ":" + st);
pw.close();
}catch(EOFException e)
{
System.out.println("End of Stream.");
}
//6.存储和恢复数据
try
{
DataOutputStream dos6 = new DataOutputStream(new BufferedOutputStream(new FileOutputStream("Data.txt")));
dos6.writeDouble(3.1415926);
dos6.writeUTF("It's PI");
dos6.writeDouble(1.41413);
dos6.writeUTF("It's squre of 2");
dos6.close();
DataInputStream dis6 = new DataInputStream(
new BufferedInputStream(
new FileInputStream("Data.txt")));
System.out.println(dis6.readDouble());
System.out.println(dis6.readUTF());
System.out.println(dis6.readDouble());
System.out.println(dis6.readUTF());
dis6.close();
}catch (EOFException e)
{
throw new RuntimeException(e);
}
//7.访问文件随机读写
RandomAccessFile raf = new RandomAccessFile("rtest.dat","rw");
for (int i = 1;i<10;i++)
raf.writeDouble(i*1.414);
raf.close();
raf = new RandomAccessFile("rtest.dat","rw");
raf.seek(5*8);
raf.writeDouble(47.00001);
raf.close();
raf = new RandomAccessFile("rtest.dat","r");
for (int i = 1;i<10;i++)
System.out.println("Value" + i + raf.readDouble());
raf.close();
}
}