Java file I/O(java 文件输入输出)

File Overview

I/O = Input/Output, here it is input to and output from programs

  Inputs can be from: Keyboard Files Etc.

  Output can be: Screen Files Etc.

Advantages of file I/O

-permanent copy

-output from one program can be input to another

-input can be automated (rather than entered manually)

Streams

  Stream: an object that either delivers data to its destination (screen, file, etc.) or that takes data from a source (keyboard, file, etc.) it acts as a buffer between the data source and destination

  Input stream: a stream that provides input to a program E.g., System.in is an input stream

  Output stream: a stream that accepts output from a program E.g., System.out is an output stream

  Examples: System.out.println(“Hi”)    connects a program to the screen

Streams作为电子设备与程序传输过程中的传输工具

Binary vs. Text Files

  All data and programs are ultimately just zeros and ones each digit can have one of two values (0 or 1),

  hence binary 1 byte = 8 bits

  Text files: the bits represent printable characters

  one byte per character for ASCII, the most common code

  for example, Java source files are text files so is any file created with a "text editor"

  Binary files: the bits represent other types of encoded information, such as executable instructions or numeric data

Text Files vs. Binary Files

  Numbe r: 127 (decimal)十进制

  Text file Three bytes: “1”, “2”, “7” ASCII (decimal): 49, 50, 55

  ASCII (binary): 00110001, 00110010, 00110111

  Binary file: One byte (byte): 01111111     Two bytes (short): 00000000 01111111    Four bytes (int): 00000000 00000000 00000000 01111111

Buffering

  Not buffered: each byte is read/written from/to disk as soon as possible “little” delay for each byte A disk operation per byte--- higher overhead

  Buffered: reading/writing in “chunks” Some delay for some bytes,

   e.g.: Assume 16-byte buffers

  Reading: access the first 4 bytes, need to wait for all 16 bytes are read from disk to memory

  Writing: save the first 4 bytes, need to wait for all 16 bytes before writing from memory to disk

  A disk operation per a buffer of bytes---lower overhead

Java I/O

  Standard IO: System.out.println("a line"); to send a line to the standard output, i.e., the screen, unless you redirect standard output

  public class RedirectSysOut {//重定向输出

    public static void main(String[] args) throws FileNotFoundException { //文件找不到时要抛出异常

    PrintStream stream1 = System.out;     //新建一个打印对象

    File aFile=new File("sysout.log");

    PrintStream stream2 = new PrintStream(new FileOutputStream(aFile));

    System.out.println("1");

    System.setOut(stream2);   //重定项屏幕输出到stream2对象中

    System.out.println("2");

    System.setOut(stream1);

    System.out.println("3");

    }

  }

Text File I/O

  Important classes for text file output (to the file)

   1)FileWriter

   2)FileOutputStream

   3)BufferedWriter

   4)PrintWriter

  Important classes for text file input (from the file):

   1)FileReader

   2)BufferedReader

  FileWriter and FileReader take file names as arguments.

  PrintWriter and BufferedReader provide useful methods for easier writing and reading.

                                              

对 TXT 文件的输入输出,使用 FileReader和FileWriter。

因为PrintWriter的范围最大,所以使用起来也最方便??

Text File Output

To open a text file for output: connect a text file to a stream for writing FileOutputStream

  fOutStream = new FileOutputStream("out.txt");

  PrintWriter pWriter = new PrintWriter(fOutStream );

Or:

  PrintWriter outputStream = new PrintWriter(new FileOutputStream("out.txt"));

  What happened is: create a PrintWriter object which uses FileOutputStream to open a text file FileOutputStream “connects” PrintWriter to a text file.

    

exa:

  public static void main(String[] args) {

    PrintWriter outputStream = null;

    try {

      outputStream = new PrintWriter(new FileOutputStream("out.txt"));  //open the file

      for (int count = 1; count <= 3; count++)

        outputStream.println(count); //write the file

      System.out.println("... written to out.txt.");

      outputStream.close();

     } catch(FileNotFoundException e){

       System.out.println("Error opening the file out.txt."+ e.getMessage());

       }

     }

   }

Overwriting a File

  In the previous example:

    -Opening an output file creates a new file if it does not already exist

    - If the file is existing,it will overwrite the file, i.e., data in the original file is lost

因为之前都是overwrite

Appending to a Text File

  To add/append to a file instead of replacing it, use a different constructor for FileOutputStream:

    outputStream = new PrintWriter(new FileOutputStream("out.txt", true));

    outputStream = new PrintWriter(new FileOutputStream("out.txt”));

    for (int count = 1; count <= 10; count++)

      outputStream.println(count);

    outputStream.close();

    outputStream = new PrintWriter(new FileOutputStream("out.txt”, true));

     for (int count = 1; count <= 10; count++)

      outputStream.println(count);

    outputStream.close();

Closing a File

  After writing a file, you should close the FileOutputStream and the PrintWriter

  fileOutputStream.close();

  outputStream.close();

-Why close the file?

  To make sure it is closed if a program ends abnormally (it could get damaged if it is left open) Flush the stream Calling close() on a wrapper stream should close the child stream.  E.g., if a PrintWriter is closed, the FileOutputStream it linked with is also closed.

-outputStream.close();

  Both the PrintWriter and FileOutputStream have been closed!!!  程序是通过PrintWriter——》FileOutputStream 接触到TXT(比如),如果关闭了 FileOutputStream 就直接断开了程序与文件的联系,就等于两者都关闭了。

Text File Input

  To open a text file for input: connect a text file to a stream for reading a BufferedReader object, which uses FileReader to open a text file FileReader “connects” BufferedReader to the text file

    FileReader s = new FileReader(“input.txt");

    BufferedReader inStream = new BufferedReader(s);

Or:

    BufferedReader inStream = new BufferedReader(new FileReader(“input.txt"));

try {

   FileReader fr=new FileReader("input.txt");

   BufferedReader inputStream = new BufferedReader(fr);

   String line = null;

   while((line=inputStream.readLine())!=null) // Check whether reached the end

    System.out.println(line); // Read a line from the file

     inputStream.close();

  } catch(FileNotFoundException e) {

  System.out.println("File not found.");

  } catch(IOException e) {

  System.out.println("Error reading from file " + fileName);

 }

StringTokenizer

There are methods to read a line and a character, but not just a single word

  StringTokenizer:

    Token: a block of (useful) text

    Delimiter: is a character used to separate items of data

    E.g., CSV files: comma-delimited

  Create a StringTokenizer instance you can specify delimiters (the character or characters that separate words)

    the default delimiters are: space, tab, and newline

        StringTokenizer(String str, String delim, boolean returnDelims) //str--The string to be separated      delim--The delimiters     returnDelims--Whether return delimiters as tokens

Read an integer by using BufferedReader

  No methods to read numbers directly Read numbers as Strings and then convert them:

  try{

    String line =inputStream.readLine();

    int value = Integer.parseInt(line);

    } catch(java.lang.NumberFormatException e){

      …

     } catch(IOException e){ …}

Creating Scanner objects

  We can create a Scanner object by invoking several different constructors.

  Scanner(File source)

  Constructs a new Scanner that produces values scanned from the specified file.

  Scanner(InputStream source)

  Constructs a new Scanner that produces values scanned from the specified input stream.

  Scanner(String source)

  Constructs a new Scanner that produces values scanned from the specified string. …

  Example (read a line from keyboard):

   Scanner sc = new Scanner (System.in);

Next Methods/hasNext methods

  Example:

  Scanner sc = new Scanner(System.in);

  int i=sc.nextInt();

  Scanner sc = new Scanner (System.in);

  System.out.print ("Enter first int: ");

  while (sc.hasNextInt()) {

    int i = sc.nextInt();

    System.out.println("You entered " + i);

    System.out.print ("Enter another int: ");

  }

Delimiters in Scanner 

  Default delimiters are: space, tab, new line

时间: 2024-08-28 11:06:52

Java file I/O(java 文件输入输出)的相关文章

java: file/outputStream/InputStream 复制文件

java i/o 复制文件 public static void main(String[] args) throws Exception { // TODO 自动生成的方法存根 if(args.length != 2) { System.out.println("您输入的参数有误"); System.exit(1); } if(args[0].equals(args[1])) { System.out.println("源文件和目标文件不能一致"); System

java file文件类操作使用方法大全

1.构造函数 [java] view plaincopy public class FileDemo { public static void main(String[] args){ //构造函数File(String pathname) File f1 =new File("c:\\zuidaima\\1.txt"); //File(String parent,String child) File f2 =new File("c:\\zuidaima",&quo

如何判断java.io.File所读取的文件编码

如何判断java.io.File所读取的文件编码 问题 java中涉及到文件读取,就经常要考虑文件编码问题.虽然程序中一般都指定UTF-8编码,但是用户总可能提交各种编码的文件(特别是windows下用户),如果对这些文件不做判断就直接按照UTF-8的方式读取的话,是肯定会乱码的. 解决方案 java原生并不支持文件编码的判断,一般都是read文件的前几个字节来判断,需要自己编写工具类,判断的编码类型也比较少.最近找到了个开源的项目juniversalchardet,能比较优雅的完成这个任务.

Windows下Java File对象创建文件夹时的一个"坑"

import java.io.File; import java.io.IOException; public class DirCreate { public static void main(String[] args) throws IOException { // TODO Auto-generated method stub String dirStr="D:"; File dir=new File(dirStr); System.out.println("====

Java file文件的写入和读取

File文件的写入 一.FileWriter 和BufferedWriter 结合写入文件 FileWriter是字符流写入字符到文件.默认情况下,它会使用新的内容代替文件原有的所有内容,但是,当指定一个true值作为FileWriter构造函数的第二个参数,它会保留现有的内容,并追加新内容在文件的末尾. BufferedWriter:缓冲字符,是一个字符流类来处理字符数据.不同于字节流(数据转换成字节FileOutPutStream),可以直接写字符串.数组或字符数据保存到文件. 默认情况,替

java移动文件夹、 慎用java file.renameTo(f)方法 、 java从一个目录复制文件到另一个目录下 、 java代码完成删除文件、文件夹 、

java移动文件夹(包含子文件和子文件夹): http://blog.csdn.net/yongh701/article/details/45070353 慎用java    file.renameTo(f)方法: http://www.cnblogs.com/mrwangblog/p/3934506.html 注意看结果,从C盘到E盘失败了,从C盘到D盘成功了.因为我的电脑C.D两个盘是NTFS格式的,而E盘是FAT32格式的.所以从C到E就是上面文章所说的"file systems"

Java——File(文件)

 public static void main(String[] args) { // getFile(); /* * 需求:  对指定目录进行所有内容的列出,(包含子目录中的内容) * */ File dir = new File("E:\\HB_JAVA解压"); listAll(dir, 0); } public static void listAll(File dir, int len) { System.out.println(getSpace(len) + dir.g

java File文件操作共用方法整理

package org.jelly.util; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.i

java file 操作之创建、删除文件及文件夹

本文章向大家讲解java文件的基本操作,包括java创建文件和文件夹.java删除文件.java获取指定目录的全部文件.java判断指定路径是否为目录以及java搜索指定目录的全部内容等.请看下面实例. 创建文件File 的两个常量(File.separator.File.pathSeparator). 直接在windows下使用\进行分割是可以的.但是在linux下就不是\了.所以,要想使得我们的代码跨平台,更加健壮,所以,大家都采用这两个常量吧. public static void cre