Java file operations method

2010-03-29  来源:本站原创  分类:Java  人气:285 

Transfer from the following code: http://lionelxx777.javaeye.com/blog/358128

Java file operations to the text of the two methods.

1. The usual practice is to use FileInputStream and FileOutputStream to carry out operations, the above two categories respectively, InputStream & OutputStream two base classes.

FileInputStream to read the data using common methods are:
FileInputStream fstream = new FileInputStream (args [0]);
DataInputStream in = new DataInputStream (fstream);
With in.readLine () to get the data, and then use in.close () close the input stream.
The complete code, see Example 1.

FileOutputStream to write the data using common methods are:
FileOutputStream out out = new FileOutputStream ( "myfile.txt");
PrintStream p = new PrintStream (out);
With p.println () to write data, and then use p.close () close the input.
The complete code, see Example 2.
2. And then that is "Reader & Writer", they can only be used to manipulate text files, while the
JDK1.1 the InputStream & OutputStream can be a text file or binary file to operate.

FileReader to read the file using common methods are:
FileReader fr = new FileReader ( "mydata.txt");
BufferedReader br = new BufferedReader (fr);
With br.readLing () to read data, and then use br.close () close the cache, use fr.close () close the file.
The complete code, see Example 3.

FileWriter to write to a file using common methods are:
FileWriter fw = new FileWriter ( "mydata.txt");
PrintWriter out = new PrintWriter (fw);
Out.println using out.print or write data to and from files, out.print and out.println the only difference is that the latter to write data, or automatically open a new line. Finished after going to remember to use out.close () Close the output, use fw.close () close the file.
The complete code, see Example 4.
Example 1:

// FileInputDemo
// Demonstrates FileInputStream and DataInputStream
import java.io.*;   

class FileInputDemo {
  public static void main(String args[]) {
    // args.length is equivalent to argc in C
    if (args.length == 1) {
      try {
        // Open the file that is the first command line parameter
        FileInputStream fstream = new FileInputStream(args[0]);
        // Convert our input stream to a DataInputStream
        DataInputStream in = new DataInputStream(fstream);
        // Continue to read lines while there are still some left to read
        while (in.available() !=0) {
          // Print file line to screen
          System.out.println (in.readLine());
        }
        in.close();
      } catch (Exception e) {
        System.err.println("File input error");
      }
    }
    else
      System.out.println("Invalid parameters");
  }
}

Example 2:

// FileOutputDemo
// Demonstration of FileOutputStream and PrintStream classes
import java.io.*;   

class FileOutputDemo
{
  public static void main(String args[])  {
  FileOutputStream out; // declare a file output object
    PrintStream p; // declare a print stream object   

try {
  // connected to "myfile.txt"
      out = new FileOutputStream("myfile.txt");
      // Connect print stream to the output stream
      p = new PrintStream( out );
      p.println ("This is written to a file");
      p.close();
    } catch (Exception e) {
      System.err.println ("Error writing to file");
    }
  }
}

Example 3:

// FileReadTest.java
// User FileReader in JDK1.1 to read a file
import java.io.*;   

class FileReadTest {
  public static void main (String[] args) {
    FileReadTest t = new FileReadTest();
    t.readMyFile();
}    

  void readMyFile() {
    String record = null;
    int recCount = 0;
    try {
FileReader fr = new FileReader("mydata.txt");
       BufferedReader br = new BufferedReader(fr);
       record = new String();
       while ((record = br.readLine()) != null) {
         recCount++;
         System.out.println(recCount + ": " + record);
}
br.close();
fr.close();
     } catch (IOException e) {
         System.out.println("Uh oh, got an IOException error!");
         e.printStackTrace();
     }
}    

}

Example 4:

// FileWriteTest.java
// User FileWriter in JDK1.1 to writer a file
import java.io.*;   

class FileWriteTest {
  public static void main (String[] args) {
    FileWriteTest t = new FileWriteTest();
    t.WriteMyFile();
}    

  void WriteMyFile() {
    try {
FileWriter fw = new FileWriter("mydata.txt");
PrintWriter out = new PrintWriter(fw);
out.print(“hi,this will be wirte into the file!”);
out.close();
fw.close();
     } catch (IOException e) {
         System.out.println("Uh oh, got an IOException error!");
         e.printStackTrace();
     }
}    

}
相关文章
  • Java file operations method 2010-03-29

    Transfer from the following code: http://lionelxx777.javaeye.com/blog/358128 Java file operations to the text of the two methods. 1. The usual practice is to use FileInputStream and FileOutputStream to carry out operations, the above two categories r

  • Java file operations enhancement tools 2010-03-29

    Java file operations enhancement tools -------------------------------------------------- ------------------------------ 2008-12-15 18:30:43 Tags: File IO commons [pushed to the technical ring] Copyright Statement: original works, and if reproduced,

  • Java file operations on the Properties Summary 2010-05-13

    Frequently used, Java file operations on the Properties, to make a summary here. Java Properties files on the operation to be "unsatisfactory", said here about the first time in general, back slowly said. 1.java read Properties files, often worn

  • Java file operations 2010-03-29

    This collection of common file operations methods, including file creation / check and delete, directory creation / check and delete, remove files in the directory, file properties to acquire, read data line by line and so on. Documents establish / c

  • Detailed Java file operations 2010-12-11

    Input and output streams in Java, we can read a sequence of bytes is called an input stream object; and we have enough to write a sequence of bytes is called an output stream. They are the abstract classes InputStream and OutputStream class. Because

  • java file operations to read and write basic 2011-01-11

    package com.hzsuwang.java; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java

  • java file operations Considerations (lesson) 2010-03-29

    File Handling Precautions 1) In order to process robustness, please check the file before the file operations to the parent directory (parentfolder) exists. File folder = new File (parentfolder_path) if (! folder.isDirectory ()) (/ / use the director

  • java file operations Daquan 2010-06-09

    1. Get the information entered by the user console Java code / ** *//** Get the information entered by the user console * @ Return * @ Throws IOException * / public String getInputMessage () throws IOException ... ( System.out.println ("Please enter

  • java file operations (recursive delete the empty folder, delete the expired file) 2010-09-19

    The operation of the document, we all write operations may, in fact, Apache, FileUtils has done a very good package, commonly used today's operational records are as follows: (1) to retain records of a few months before the provisions are as follows:

  • Java file operations (transfer) 2010-10-10

    One. Get the console user input / ** Get the information entered by the user console * @ Return * @ Throws IOException * / public String getInputMessage () throws IOException { System.out.println ("Please enter your command:"); byte buffer [] =

  • Java file operations Daquan read and write 2010-11-14

    One. Get the console user input / ** *//** Get the console user input * @ Return * @ Throws IOException * / public String getInputMessage () throws IOException ... { System.out.println ("Please enter your command:"); byte buffer [] = new byte [1

  • Java SE 7 file operations (1)-Path Class Description 2010-03-24

    Taken from the developers of the Sky 1. Path of the concept of <br /> file system files will be organized and stored in medium, usually one or more of the hard disk. Currently, most of the file system tree is a way to store documents. In the top of

  • New features of Java SE 7 file operations (6) - create a file and read the file 2010-04-03

    Transferred from the developer's sky In this paper we discuss how to create files in NIO2 in, read the file and write files. NIO2 offers a variety of methods to create documents, allows us to create the file when you can specify some initial attribut

  • New features of Java SE 7 file operations (9) - traverse the directory tree 2010-04-13

    Transferred from the developer's sky In some cases, we may need to traverse the entire directory tree, such as the need to find all. Java file. Java SE 7 provides a very convenient way to achieve this kind of functionality. Implementation of Java SE

  • JAVA write file operations Gadgets 2010-12-13

    Long time no written code, very, very strange, a lot of things are forgotten, wrote a small tool that small problem there, get me a whole night, and later that knows the problem, but it still is in view of solving complex, thought did not need a gadg

  • java file write operation 2010-03-29

    package com.test2; import java.io.*; /** * @desc java File write operations * @author zhaozhi3758 * */ public class FileWriteT { // The following method file is created automatically public void writeToFile1(String path,String str) throws FileNotFoun

  • JAVA IO operations summary - node flow and processing flow 2010-07-30

    This article is taken from http://www.svn8.com/java/yy/20100420/29575.html summed it up very well looked after size-fits-io summary, look at this one a kind of enlightened feeling. JAVA IO operations summary - node and processing streams in accordanc

  • JSP file operations file creation / check and delete 2010-09-06

    JSP file operations Daquan instance document creation / check and delete <% @ Page contentType = "text / html; charset = gb2312"%> <% @ Page import = "java.io. *"%> <html> <head> <title> documents to estab

  • java file reading and writing Daquan 2010-12-05

    Text file using the Java method operating Detailed Summary: java does not support the original text files for processing, in order to compensate for this deficiency was introduced in the first two classes Reader and Writer java does not support the p

  • java file operation 2010-03-29

    java text file operations personally think that the most complicated to modify operation! Need to rewrite the entire text! public class txtfile ( public void txtfileQ () throws IOException (/ / txt file query FileReader fr = new FileReader ( "c: / /