java中输入和输出主要有字节流和字符流两大类,两类都有输入和输出的操作,在字节流中输出数据主要使用OutputStream类完成,输入使用InputStream类;
OutputStream类是一个抽象类,如果要使用此类,则首先必须通过子类实例化对象,可以通过FileOutputStream子类向上转型,可以OutputStream类实例化,
其常用的方法有:
其Outputstream类具体操作代码如下:
package test;
import java.io.OutputStream;
import java.io.FileOutputStream;
import java.io.File;
public class FIleoutputSteam_test {
public static void main(String args[]) throws Exception{
OutputStream out=new FileOutputStream("d:"+File.separator+"AAAA.txt",true); //true参数表示追加
String str="\r\nhello world!!!!!"; //\r\n表示换行
// OutputStream类中写入只能以字节流的形式写入
String str1="\r\n周美旭";
byte b[]=str.getBytes();
byte b2[]=str1.getBytes();
out.write(b);
out.write(b2);
out.close();
}
}
inputstream类具体操作代码如下:
package test;
import java.io.File;
import java.io.InputStream;
import java.io.FileInputStream;
public class InputStream_test {
public static void main(String args[])throws Exception{
File f=new File("d:"+File.separator+"AAAA.txt");
int i=(int)f.length(); //可以获得文件长度的方法
System.out.println("文件的长度为:"+i);
InputStream input=new FileInputStream(f);
byte b[]=new byte[(int)f.length()];
int x=input.read(b);//将内容读到byte数组里面,同时返回读入的个数
System.out.println("读入个数为"+x+"个");
input.close();
System.out.println("内容为:"+new String(b,0,x)); //产生的一个新的字符串长度,其长度的在0到x之间
//也可以用下面的方式读入
InputStream input1=new FileInputStream(f);
byte b1[]=new byte[i];
for(int j=0;j<b1.length;j++){
b1[j]=(byte)input1.read();
}
input.close();
System.out.println("内容为:"+new String(b));
//也可以配合while来读入
InputStream input2=new FileInputStream(f);
int len=0,temp=0;
byte b2[]=new byte[1034];
while((temp=input2.read(b2))!=-1){
b[len]=(byte)temp;
len++;
}
System.out.println("内容为:"+new String(b,0,len));
input2.close();
}
}
字符流的操作主要是Writer类和Reader类
这两个类也是抽象类分别通过FileWriter和FIleReader类来实例化操作
FIlewriter具体操作如下:
package test;
import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import com.sun.org.apache.bcel.internal.classfile.Field;
public class Writer_test {
public static void main(String args[]) throws Exception{
File f=new File("d:"+File.separator+"AA.txt");
Writer out=new FileWriter(f,true);
String s="\r\n周美旭\r\nzhoumeixu";
out.write(s);
out.close();
}
}
FileReader类的具体操作如下:
package test;
import java.io.File;
import java.io.Reader;
import java.io.FileReader;
public class Reader_test {
public static void main(String args[])throws Exception{
File f=new File("d:"+File.separator+"AA.txt");
Reader in=new FileReader(f);
int x=(int)f.length();
int temp=0;
int len=0;
char c[]=new char[x];
while((temp=in.read())!=-1){
c[len]=(char) temp;
len++;
}
in.close();
System.out.println("内容为:"+new String(c,0,len));
}
}