流的输入及输出均是对程序而言
File src = new File("D:/aa", "a.txt");
Inputstream in = new FileInputStream(src);
byte[] car = new byte[10];
int len = 0;
while (-1 != (len = in.read(car))) {
String info = new String(car, 0, len);
System.out.println(info);
}
read()返回读入长度,为-1时结束
2. 4)、读取结束后关闭输入流
in.close();
try {
in = new FileInputStream(src);
byte[] car = new byte[10];
int len = 0;
while (-1 != (len = in.read(car))) {
String info = new String(car, 0, len);
System.out.println(info);
}
} catch (FileNotFoundException e) {
System.out.println("文件读取失败");
} catch (IOException e) {
System.out.println("文件流操作失败");
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
System.out.println("关闭输入流失败");
}
}
}
File src = new File("D:/aa", "a.txt");
Outputstream in = new FileOutputStream(src);
String str = "simple\n";
out.write(str.getBytes());
out.flush();
flush()方法使流中的数据写入文件
2. 4)、读取结束后关闭输出流
out.close();
try {
out = new FileOutputStream(src, true);
String str = "simple\n";
out.write(str.getBytes());
out.flush();
} catch (FileNotFoundException e) {
System.out.println("文件不存在");
} catch (IOException e) {
System.out.println("文件流操作失败");
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
System.out.println("关闭输出流失败");
}
}
}
package cn.hxh.io.filebyte;
import java.io.*;
public class myInputStream {
public static void main(String[] args) {
File src = new File("D:/aa", "a.txt");
InputStream in = null;
try {
in = new FileInputStream(src);
byte[] car = new byte[10];
int len = 0;
while (-1 != (len = in.read(car))) {
String info = new String(car, 0, len);
System.out.println(info);
}
} catch (FileNotFoundException e) {
System.out.println("文件读取失败");
} catch (IOException e) {
System.out.println("文件流操作失败");
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("关闭输入流失败");
}
}
}
}
}
package cn.hxh.io.filebyte;
import java.io.*;
public class myOutputStream {
public static void main(String[] args) {
File src = new File("D:/aa", "a.txt");
OutputStream out = null;
try {
out = new FileOutputStream(src, true);
String str = "simple\n";
out.write(str.getBytes());
out.flush();
} catch (FileNotFoundException e) {
System.out.println("文件不存在");
} catch (IOException e) {
System.out.println("文件流操作失败");
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
System.out.println("关闭输出流失败");
}
}
}
}
}