JAVA IO操作

来源:互联网 发布:生成淘宝店铺代码 编辑:程序博客网 时间:2024/06/01 10:36
下面介绍使用Java实现文件的读写,步骤如下:
1 使用File类找到一个文件
2使用字节/字符流 进行实例化操作
3进行读或写操作
4关闭:使用close()方法。

具体实现代码:

package com.gengxin.streamDemo;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;/** * StreamDemo  * 先写入到F:\testio.txt,后从此文件中读出内容 * @author WER1234S */public class StreamDemo {public static void main(String[] args) throws IOException {// 使用file 类找到文件File file = new File("F:" + File.separator + "testio.txt");// 使用子类进行输出流的实例化OutputStream output = null;output = new FileOutputStream(file, true); //以追加的方式写入// 定义要写入的数据String str = "Hello World !\r\n";byte[] out = str.getBytes();for (int i = 0; i < out.length; i++) {// 进行读或写操作output.write(out[i]);// out.write(b);}// 使用子类进行输入流的实例化InputStream input = null;input = new FileInputStream(file);//获取要读取文件的长度byte[]in = new byte[(int) file.length()];for(int j = 0; j<in.length; j++){in[j] = (byte) input.read();}System.out.println(new String(in));// 关闭流input.close();output.close();}}

此程序 先将Hello World!  写入到F:\testio.txt,后从此文件中读出。由于篇幅有限,程序统一抛出IOException异常。