OutputStream和InputStream实例
import java.io.File;
import java.io.OutputStream;
import java.io.FileOutputStream;
public class OutputStreamDemo03
{
public static void main(String args[]) throws Exception{
File file = new File( "H:"+File.separator+"programTest"+File.separator+"IO"+File.separator+"字符流与字符流"+File.separator+"test.txt");
OutputStream out = null;
out = new FileOutputStream(file,true); //是否追加
String str = " 新增非覆盖!";
byte[] b = str.getBytes();
for(byte temp:b){
out.write(temp);
}
//out.write(b);
//out.flush();
out.close();
out = new FileOutputStream(file,true); //是否追加
str = " \r\n我是换行的哦!"; // \r\n换行
b = str.getBytes();
for(byte temp:b){
out.write(temp);
}
//out.write(b);
//out.flush();
out.close();
}
};
import java.io.File;
import java.io.InputStream;
import java.io.FileInputStream;
public class InputStreamDemo01
{
public static void main(String args[]) throws Exception{
File file = new File( "H:"+File.separator+"programTest"+File.separator+"IO"+File.separator+"字符流与字符流"+File.separator+"test.txt");
InputStream input = null;
input = new FileInputStream(file); //是否追加
String str = " 新增非覆盖!";
byte[] b = new byte[1024]; //所有内容读到此数组中
input.read(b);
input.close();
System.out.println("读取到的字符串为:"+new String(b));
}
};
//此时内容已读取过来,不过有很多空格,因为b的大小为1024
修改为
import java.io.File;
import java.io.InputStream;
import java.io.FileInputStream;
public class InputStreamDemo01
{
public static void main(String args[]) throws Exception{
File file = new File( "H:"+File.separator+"programTest"+File.separator+"IO"+File.separator+"字符流与字符流"+File.separator+"test.txt");
InputStream input = null;
input = new FileInputStream(file); //是否追加
String str = " 新增非覆盖!";
byte[] b = new byte[1024]; //所有内容读到此数组中
int len = input.read(b);
input.close();
System.out.println("读取到的字符串为:"+new String(b,0,len));
}
};
高效方式
byte[] b = new byte[(int)f.length()]; //开辟文件大小的空间
input.read(b);
input.close();
System.out.println("读取到的字符串为:"+new String(b));
byte[] b = new byte[(int)file.length()]; //所有内容读到此数组中
for(int i=0;i<b.length;i++){
b[i] = (byte)input.read();
}
input.close();
System.out.println("读取到的字符串为:"+new String(b));
带背景字体部分适用于知道文件大小时可用,input.read()读到文件末尾时值为-1,
byte[] b = new byte[(int)f.length()]; //开辟文件大小的空间
int len = 0;
int temp = 0;
while((temp = input.read()) != -1)
{
b[len] = (byte)temp;
len++;
}
input.close();
System.out.println("读取到的字符串为:"+new String(b,0,len));
带横线部分适合于不知道所读内容大小时,通过input.read()读到文件末尾时值为-1进行判断输出