FileInputStream
和FileOutputStream
用于从本机文件系统上的文件读取数据并将数据写入。
以下是使用FileInputStream
从文件读取数据的示例。
文件:FileInputStreamExample.java –
package com.yiibai.tutorial.io; import java.io.File; import java.io.FileInputStream; import java.io.IOException; /** * @author yiibai * FileInputStreamExample.java * Nov 5, 2016 */ public class FileInputStreamExample { public static void main(String[] args) { File file=new File("file.txt"); try { FileInputStream fileInputStream=new FileInputStream(file); int b; while((b=fileInputStream.read())!=-1){ System.out.print((char)b); } fileInputStream.close(); } catch (IOException e) { e.printStackTrace(); } } }
执行上面示例代码,得到以下结果:
This is an example of reading data from file.
以下是使用FileOutputStream
将数据写入文件的示例。文件:FileOutputStreamExample.java –
package com.yiibai.tutorial.io; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; /** * @author yiibai * FileOutputStreamExample.java * Nov 5, 2016 */ public class FileOutputStreamExample { public static void main(String[] args) { String data="This is an example of writing data to a file."; File file=new File("outfile.txt"); try { FileOutputStream fileOutputStream = new FileOutputStream(file); fileOutputStream.write(data.getBytes()); fileOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } } }
执行上面示例代码,得到以下结果:
This is an example of writing data to a file.
以下程序使用两个文件流将数据从一个文件复制到另一个文件。
文件:FileStreamExample.java –
package com.yiibai.tutorial.io; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; /** * @author yiibai * FileStreamExample.java * Nov 5, 2016 */ public class FileStreamExample { public static void main(String[] args) { File inFile=new File("input.txt"); File outFile=new File("output.txt"); try { FileInputStream fileInputStream=new FileInputStream(inFile); FileOutputStream fileOutputStream=new FileOutputStream(outFile); int i; while((i=fileInputStream.read())!=-1){ fileOutputStream.write(i); } fileInputStream.close(); fileOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } } }
输入文件 – input.txt 的内容:
This is an example of the FileInputStream and FileOutputStream.
输出文件 – output.txt 的内容:
This is an example of the FileInputStream and FileOutputStream.
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/264115.html