Java程序读取与写入数据
输入流是从文件读取数据,是一个拉取数据的过程;输出流是将数据写入到文件,是一个推送数据的过程。
为了便于理解输入输出流,前面都是以文件为数据源来讨论的。其实,Java的输入与输出流支持任何数据源的读取与写入,包括键盘、文件、网络、数据库等数据源。
输入流和输出流按读取和写入的数据单位可分为字节流和字符流,字节流是以字节为单位传输数据的流,字符流是以字符为单位传输数据的流。
Java所提供的输入流和输出流类封装在Java.io包中
文件字节输出流关联指定文件路径的文件,数据通过文件字节输出流以字节为单位输出并保存到文件中。文件字节输出流继承自OutputStream类,并实现OutputStream类的各种方法。
文件字节输出流的构造方法语法如下:
语法1:以File对象为参数创建FileOutputStream实例
new FileOutputStream(File file)1语法2:以文件对象的绝对路径为参数创建FIleOutputStream实例
new FileOutputStream(String filepath)你好,java的API中提供了用于对象输入输出文件的操作,实例代码如下:
定义单词类如下(注意:你定义的类要实现Serializable接口)
public class Words implements Serializable {
private int size
private String[] words
public Words(){}
public Words(String...strs){
this.words = strs
this.size = strs.length
}
@Override
public String toString() {
return "Words{" +
"size=" + size +
", words=" + Arrays.toString(words) +
'}'
}
}
2. 对象输入输出api测试类
public class ObjIOTest {
public static void main(String[] args) {
String path = "d:/myIOTest.txt"
ObjIOTest objIOTest = new ObjIOTest()
Words words = new Words("hello", "my", "dear", "friend")
try {
objIOTest.writeObject(path,words)
Words wordsFromFile = (Words)objIOTest.readObject(path)
System.out.println(wordsFromFile.toString())
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace()
}
}
//java serialize a object to file
public void writeObject(String path,Object map) throws IOException{
File f=new File(path)
FileOutputStream out=new FileOutputStream(f)
ObjectOutputStream objwrite=new ObjectOutputStream(out)
objwrite.writeObject(map)
objwrite.flush()
objwrite.close()
}
// read the object from the file
public Object readObject(String path) throws IOException, ClassNotFoundException{
FileInputStream in=new FileInputStream(path)
ObjectInputStream objread=new ObjectInputStream(in)
Object map=objread.readObject()
objread.close()
return map
}
}
把两段代码拷贝到一个包下即可运行了,希望您的问题得到解答