Java流式输入输出-面向字节

来源:互联网 发布:小提琴音准软件 编辑:程序博客网 时间:2024/05/23 20:45
package inputoutput;
import java.io.*;
public class shurushuchu {


/**
* @param args
*/
/* 面向字节输入流
* InputStreamlei
* 方法:int read(),都一个字节
*   int read(byte b[]) 读多个字节到字节数组中
*   void mark();在当前位置指针处做一个标记
*   void reset();将位置指针返回标记处
*   void close();关闭流

* FileInputStream   以File对象或字符串表示的文件名    用于实现对磁盘文件的数据读取

* read()方法的返回值是字节,读取到文件的末尾时返回-1,利用这一特点来组织循环 while(byteread!=-1){System.out.print();byteread=inflie.read();}

* DataInputStream  基本数据类型的读取方法:readByte();readBoolean();readChar();readInt()


* 面向字节输出流

* OutputStream
* 方法: void write(int b):将参数b的低字节写入输出流
*    void write(byte b[]):将字节数组全部写入输出流
* void close():关闭输出流

*FileOutputStream 参数为文件名,如果 文件名不存在,系统将自动新建文件
*
*DataOutputStream 实现基本数据的输出方法 writeByte(int);writeBytes(String),writeBoolean(boolean);writeChars(String)...
* */
public static void main(String[] args) {
// TODO Auto-generated method stub
int number=0;
try{
File f=new File("C:\\Users\\pc\\Desktop\\新建文本文档.txt");
FileInputStream infile=new FileInputStream(f);//使用此方法时必须加上异常处理方法FileNotFoundException
int byteread=infile.read();
while(byteread!=-1){
System.out.println((char)byteread);
byteread=infile.read();
}
InputStreamReader s=new InputStreamReader(infile);
LineNumberReader In=new LineNumberReader(s);
boolean eof=false;
while(!eof){
String x=In.readLine();
if(x==null)
eof=true;
else
System.out.println(In.getLineNumber()+":"+x);
}


FileOutputStream file=new FileOutputStream("C:\\Users\\pc\\Desktop\\x.txt");
DataOutputStream out=new DataOutputStream(file);
for(int n=11;n<100;n++){
if(isprime(n)&&isprime(n+2)){
out.writeInt(n);
out.writeInt(n+2);
}
}
out.close();



FileInputStream file1=new FileInputStream("C:\\Users\\pc\\Desktop\\x.txt");
DataInputStream in=new DataInputStream(file1);
while(true){
int n1=in.readInt();
int n2=in.readInt();
System.out.println(n1+","+n2);
}
}catch(FileNotFoundException e){System.out.println("file not find");}
catch(IOException e){}




}
public static boolean isprime(int n){
for(int k=2;k<Math.sqrt(n);k++){
if(n%k==0)
return false;
}
return true;
}

}
0 0