import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.FileInputStream;
public class InputStreamDemo {
public static void main(String[] args) {
//File.separator代表的是“ / ”,java虚拟机会根据操作系统来转化路径分隔符
String info = "d:"+File.separator+"text.txt";//路径InputStream is = null;
try {
is = new FileInputStream(info);
byte[] b = new byte[1024];
int temp = 0;
while((temp=is.read(b))!=-1){
//下面也可以这样写:new String(b); 但是由于b大是1024,如果文件的大小不够1024就会以空格填充
//所以通常我们使用下面这种方式:
System.out.println(new String(b,0,temp));
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public class OutputStreamDemo {
public static void main(String[] args) {
String path = "d:"+File.separator+"file"+File.separator+"aaa.txt";
File f = new File(path);
OutputStream os = null;
String info = "This is Sunny today";
try {
f.createNewFile();
//字节流
os = new FileOutputStream(path,true);//如果加true代表的是不会覆盖原本的内容,追加到文字,如果不加true就会覆盖原先的内容
os.write(info.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}