Java学习路程之File

来源:互联网 发布:oracle linux安装教程 编辑:程序博客网 时间:2024/04/27 22:19

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


0 0
原创粉丝点击