• Java读写文件


    FileInputStream

    该流用于从文件读取数据,它的对象可以用关键字 new 来创建。

    有多种构造方法可用来创建对象。

    可以使用字符串类型的文件名来创建一个输入流对象来读取文件:

    InputStream f = new FileInputStream("C:/java/hello");

    也可以使用一个文件对象来创建一个输入流对象来读取文件。我们首先得使用 File() 方法来创建一个文件对象:

    File f = new File("C:/java/hello");
    InputStream out = new FileInputStream(f);

    FileOutputStream

    该类用来创建一个文件并向文件中写数据。

    如果该流在打开文件进行输出前,目标文件不存在,那么该流会创建该文件。

    有两个构造方法可以用来创建 FileOutputStream 对象。

    使用字符串类型的文件名来创建一个输出流对象:

    OutputStream f = new FileOutputStream("C:/java/hello")

    也可以使用一个文件对象来创建一个输出流来写文件。我们首先得使用File()方法来创建一个文件对象:

    File f = new File("C:/java/hello");
    OutputStream f = new FileOutputStream(f);

    实例

    下面是一个演示 InputStream 和 OutputStream 用法的例子:

    import java.io.*;
     
    public class fileStreamTest {
        public static void main(String args[]) {
            try {
                byte bWrite[] = { 11, 21, 3, 40, 5 };
                OutputStream os = new FileOutputStream("test.txt");
                for (int x = 0; x < bWrite.length; x++) {
                    os.write(bWrite[x]); // writes the bytes
                }
                os.close();
     
                InputStream is = new FileInputStream("test.txt");
                int size = is.available();
     
                for (int i = 0; i < size; i++) {
                    System.out.print((char) is.read() + "  ");
                }
                is.close();
            } catch (IOException e) {
                System.out.print("Exception");
            }
        }
    }

    参考资料

    菜鸟教程

  • 相关阅读:
    TestCase NotePad3.0 of robotium
    一些小的东东
    面试ASP.NET程序员的笔试题和机试题
    verify the text views its easy to use getView from the adapter
    巧用Cacls.exe命令来修改文件访问控制权限
    Monkey test
    monkeyrunner test
    Autotest NotePad with robotium
    网站新技术知识
    序列化
  • 原文地址:https://www.cnblogs.com/xumaomao/p/12818619.html
Copyright © 2020-2023  润新知