Java中IO函数的使用方法及其操作技巧
Java中的IO函数是Java语言中常用的函数,其主要功能是在程序中读取和写入数据。下面将介绍Java中IO函数的使用方法及其操作技巧。
1. 读取数据
Java中读取数据的函数主要有:
① FileReader:
FileReader fr = new FileReader("test.txt");
int ch = -1;
while ((ch = fr.read()) != -1) {
System.out.print((char) ch);
}
fr.close();
② FileInputStream:
FileInputStream fis = new FileInputStream("test.txt");
int ch = -1;
while ((ch = fis.read()) != -1) {
System.out.print((char) ch);
}
fis.close();
③ BufferedReader:
BufferedReader br=new BufferedReader(new FileReader("test.txt"));
String str = "";
while ((str = br.readLine()) != null) {
System.out.println(str);
}
br.close();
2. 写入数据
Java中写入数据的函数主要有:
① FileWriter:
FileWriter fw = new FileWriter("test.txt");
fw.write("Java IO函数使用
");
fw.close();
② FileOutputStream:
FileOutputStream fos = new FileOutputStream("test.txt");
String str = "Java IO函数使用
";
fos.write(str.getBytes());
fos.close();
3. 操作技巧
① 使用BufferedInputStream和BufferedOutputStream
对于大文件的读写,使用BufferedInputStream和BufferedOutputStream可以大大提高效率:
BufferedInputStream bis = new BufferedInputStream(new FileInputStream("test.txt"));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("newtest.txt"));
byte[] b = new byte[1024];
int len = -1;
while ((len = bis.read(b)) != -1) {
bos.write(b, 0, len);
}
bis.close();
bos.close();
② 使用ObjectInputStream和ObjectOutputStream
可以使用ObjectInputStream和ObjectOutputStream读写对象,这里需要将对象类实现Serializable接口:
class Student implements Serializable {
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + "]";
}
}
public static void main(String[] args) throws Exception {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("student.txt"));
oos.writeObject(new Student("张三", 20));
oos.close();
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("student.txt"));
Student s = (Student) ois.readObject();
System.out.println(s);
ois.close();
}
总之,在Java的IO函数中,读取和写入数据是经常会用到的,上述操作技巧可以提高读写数据的效率以及拓宽函数的使用范围,更好地应用到实际开发中。
