文件
输入、输出流
字节流
try {
System.out.println("以字节为单位读取文件内容,一次读一个字节:");
// 一次读一个字节
in = new FileInputStream(file);
int tempbyte;
while ((tempbyte = in.read()) != -1) {
System.out.write(tempbyte);
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
read方法的返回值是读到的一个字节的int,其范围是0-255,结束时这个值是-1
FileInputStream fileInputStream = new FileInputStream(in);
FileOutputStream fileOutputStream = new FileOutputStream(out);
byte[] a = new byte[100];
while ((num = fileInputStream.read(a)) != -1) {
//System.out.println(num);
fileOutputStream.write(a);
}
字符流
FileReader fileReader = new FileReader(in);
FileWriter fileWriter = new FileWriter(out);
char[] a = new char[100];
while ((num = fileReader.read(a)) != -1) {
System.out.println(num);
fileWriter.write(a);
}
按行读写(处理流)
处理流可以看做是节点流的包装
System.out.println("以行为单位读取文件内容,一次读一整行:");
reader = new BufferedReader(new FileReader(in));
writer = new BufferedWriter(new FileWriter(out));
String tempString = null;
int line = 1;
// 一次读入一行,每一行都放在了一个字符串中,直到读入null为文件结束
while ((tempString = reader.readLine()) != null) {
System.out.println("line"+line+++":"+tempString);
writer.write(tempString);
//写入一个换行符
writer.newLine();
}
数据流
public static void useDataInput() throws Exception{
DataInputStream dis = null;
DataOutputStream dos = null;
FileInputStream is = null;
FileOutputStream fos = null;
int[] i = {128,250,430,520,820};
try{
fos = new FileOutputStream("D:\\5.txt");
dos = new DataOutputStream(fos);
for(int j:i)
{
dos.writeInt(j);
}
dos.flush();
is = new FileInputStream("D:\\5.txt");
dis = new DataInputStream(is);
// available stream to be read
while(dis.available()>0)
{
// read four bytes from data input, return int
int k = dis.readInt();
// print int
System.out.print(k+" ");
}
}catch(Exception e){
e.printStackTrace();
}finally{
if(is!=null)
is.close();
if(dis!=null)
dis.close();
if(fos!=null)
fos.close();
if(dos!=null)
dos.close();
}
}
}
在JAVA中,一个long类型8个字节,如果把这个数转换成byte数组,则会耗费很多的内存,
转换流
InputStreamReader和OutputStreamWriter,把字节流转成字符流
InputStreamReader isr = null;
OutputStreamWriter dsw = null;
char[] c = new char[1024];
isr = new InputStreamReader(new FileInputStream("D:\\5.txt"));
dsw = new OutputStreamWriter(new FileOutputStream("D:\\6.txt"));
while (isr.read() != -1) {
dsw.write(c);
}
标准输入输出
在JAVA语言中,我们通过Scanner类,实现系统输入(System.in)
查看API,可以发现这个类的构造方法有下面几种:字符串、文件、流
try {
File file = new File("e:"+File.separator+"io.txt");
Scanner c = new Scanner(file);
while (c.hasNext()){
System.out.println(c.nextLine());
}
}catch (FileNotFoundException e){
e.printStackTrace();
}
主要方法:
hasNext:判断输入是否结束
next:接收输入的字符串(以空格、回车作为结束标志)
nextLine:接收输入的字符串(以回车做为结束标志)
在上面的例子中,输出是
asas asffdg
hjfgdgfdgnb
fghfhfgh
使用c.next(),输出是
asas
asffdg
hjfgdgfdgnb
fghfhfgh
密码输入:
Console con = console();
String unername = con.readLine("User name");
char[] password = con.readPassword();
JAVA1.6后使用Console类接收密码和用户名
使用开发环境会报空指针异常
序列化,请参考 JAVA对象的序列化
NIO
新的带缓冲的无阻塞IO