FileInputStream和FileOutPutStream
一个流可以理解为一个数据的序列,输入流表示从源中读取数据,输出流表示向一个目标中写入数据。
FileInputStream:是用来从文件中读取数据,他的对象可以用new关键字创建,也有多种构造方法创建对象。
InputStream f = new FileInputStream("c:/java.txt");
或者
File f = new File("C:/java/hello");
InputStream f = new FileInputStream(f);
FileOutputStream:是用来向一个目标中写入数据的。如果该流在打开文件进行输出前,目标文件不存在,那么该流会创建该文件。有两个构造方法可以用来创建
OutputStream out=new FileOutputStream("c:/java.txt");或者File file=new File("c:/java.txt");
OutputStream out=new FileOutputStream(file); 有了上面的对象,就可以对文件进行读写了!
public static void main(String[] args) throws IOException { File file=new File("c:/java.txt");
file.createNewFile();
FileWriter writer=new FileWriter(file);
writer.append("hello world");
writer.flush();
writer.close();
FileReader reader=new FileReader(file);
char[] cha=new char[30];
reader.read(cha);
for (char c : cha) {
System.out.print(c);
}
reader.close();
}输出结果为:hello world
本文介绍了如何使用Java的FileInputStream和FileOutputStream类进行文件的基本读写操作,包括创建文件、写入文本、读取文本等步骤。
1080

被折叠的 条评论
为什么被折叠?



