Java语言深入 JAVA之精髓IO流(2)

分类: J2SE   出处:iocblog整理  更新时间:2008-07-31   添加到收藏  

4. i/o应用的一个例子
import java.io.*;
public class testio{
public static void main(string[] args)
throws ioexception{
//1.以行为单位从一个文件读取数据
bufferedreader in = 
new bufferedreader(
new filereader("f:\nepalon\testio.java"));
string s, s2 = new string();
while((s = in.readline()) != null)
s2 += s + " ";
in.close();

//1b. 接收键盘的输入
bufferedreader stdin = 
new bufferedreader(
new inputstreamreader(system.in));
system.out.println("enter a line:");
system.out.println(stdin.readline());

//2. 从一个string对象中读取数据
stringreader in2 = new stringreader(s2);
int c;
while((c = in2.read()) != -1)
system.out.println((char)c);
in2.close();

//3. 从内存取出格式化输入
try{
DataInputStream in3 =
new DataInputStream(
new ByteArrayInputStream(s2.getBytes()));
while(true)
System.out.println((char)in3.readByte());
}(来源 www.iocblog.net)
catch(EOFException e){
System.out.println("End of stream");
}

//4. 输出到文件
try{
BufferedReader in4 = new BufferedReader(new StringReader(s2));
PrintWriter out1 =
new PrintWriter(
new BufferedWriter(
new FileWriter("F:\\nepalon\\ TestIO.out")));
int lineCount = 1;
while((s = in4.readLine()) != null)
out1.println(lineCount++ + ":" + s);
out1.close();
in4.close();
}
catch(EOFException ex){
System.out.println("End of stream");
}

//5. 数据的存储和恢复
try{
DataOutputStream out2 =
new DataOutputStream(
new BufferedOutputStream(
new FileOutputStream("F:\\nepalon\\ Data.txt")));
out2.writeDouble(3.1415926);
out2.writeChars("\nThas was pi:writeChars\n");
out2.writeBytes("Thas was pi:writeByte\n");
out2.close();
DataInputStream in5 =
new DataInputStream(
new BufferedInputStream(
new FileInputStream("F:\\nepalon\\ Data.txt")));
BufferedReader in5br =
new BufferedReader(
new InputStreamReader(in5));
System.out.println(in5.readDouble());
System.out.println(in5br.readLine());
System.out.println(in5br.readLine());
}
catch(EOFException e){
System.out.println("End of stream");
}

//6. 通过RandomAccessFile操作文件

上一页 [1] [2] [3] 下一页


Tag: IO



文章整理:iocblog
版权申明:本站文章均来自网络,如有侵权,请联系我们,我们收到后立即删除,谢谢!
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有。