Java 對文件進行讀寫操作的例子很多
一次分析
一.在 JDK
InputStream 中的 FileInputStream 類似一個文件句柄
OutputStream 中我們有 FileOutputStream 這個對象
用FileInputStream 來讀取數據的常用方法是
FileInputStream fstream = new FileInputStream(args[
DataInputStream in = new DataInputStream(fstream);
用 in
完整代碼見 Example
用FileOutputStream 來寫入數據的常用方法是
FileOutputStream out out = new FileOutputStream(
PrintStream p = new PrintStream( out );
用 p
完整代碼見 Example
二.在 JDK
JDK
用FileReader 來讀取文件的常用方法是
FileReader fr = new FileReader(
BufferedReader br = new BufferedReader(fr);
用 br
完整代碼見 Example
用 FileWriter 來寫入文件的常用方法是
FileWriter fw = new FileWriter(
PrintWriter out = new PrintWriter(fw);
在用out
入數據或會自動開一新行
完整代碼見 Example
Example
// FileInputDemo
// Demonstrates FileInputStream and DataInputStream
import java
class FileInputDemo {
public static void main(String args[]) {
// args
if (args
try {
// Open the file that is the first command line parameter
FileInputStream fstream = new FileInputStream(args[
// 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
// Print file line to screen
System
}
in
} catch (Exception e) {
System
}
}
else
System
}
}
Example
// FileOutputDemo
// Demonstration of FileOutputStream and PrintStream classes
import java
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
out = new FileOutputStream(
// Connect print stream to the output stream
p = new PrintStream( out );
p
p
} catch (Exception e) {
System
}
}
}
Example
// FileReadTest
// User FileReader in JDK
import java
class FileReadTest {
public static void main (String[] args) {
FileReadTest t = new FileReadTest();
t
}
void readMyFile() {
String record = null;
int recCount =
try {
FileReader fr = new FileReader(
BufferedReader br = new BufferedReader(fr);
record = new String();
while ((record = br
recCount++;
System
}
br
fr
} catch (IOException e) {
System
e
}
}
}
Example
// FileWriteTest
// User FileWriter in JDK
import java
class FileWriteTest {
public static void main (String[] args) {
FileWriteTest t = new FileWriteTest();
t
}
void WriteMyFile() {
try {
FileWriter fw = new FileWriter(
PrintWriter out = new PrintWriter(fw);
out
out
fw
} catch (IOException e) {
System
e
}
}
}
From:http://tw.wingwit.com/Article/program/Java/JSP/201311/19453.html