import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.PrintWriter;
/**
* File
*/
/**
* @author fhwei 2006-11-9 下午04:56:28
*/
public class FileDemo {
String fileName = "e://file.txt";
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
FileDemo fd = new FileDemo();
fd.fileInputStream();
}
/**
* 文件输出流是用于将数据写入 File 或 FileDescriptor 的输出流 用于写入诸如图像数据之类的原始字节的流
*/
void fileOutputStream() {
try {
FileOutputStream fos = new FileOutputStream(fileName);
/* 创建新的打印流 */
PrintStream ps = new PrintStream(fos);
/* 打印字符串 */
ps.println("This is written to a file");
ps.close();
fos.close();
} catch (Exception e) {
System.err.println("Error writing to file");
}
}
/**
*
* 2006上午10:41:08
*/
void WriteMyFile() {
try {
/* 在给出 File 对象的情况下构造一个 FileWriter 对象 */
FileWriter fw = new FileWriter(fileName);
/* 创建不带自动行刷新的新 PrintWriter */
PrintWriter pw = new PrintWriter(fw);
/* 打印 String,然后终止该行 */
pw.println("hi,this will be wirte into the file!");
pw.close();
fw.close();
} catch (IOException e) {
System.out.println("Uh oh, got an IOException error!");
e.printStackTrace();
}
}
/**
*
* 2006上午10:41:16
*/
void readMyFile() {
String record = null;
int recCount = 0;
try {
FileReader fr = new FileReader(fileName);
/* 从字符输入流中读取文本,缓冲各个字符,从而提供字符、数组和行的高效读取 */
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();
}
}
/**
*
* 2006上午10:41:23
*/
/* FileInputStream */
void fileInputStream() {
String record = null;
try {
FileInputStream fstream = new FileInputStream(fileName);
BufferedReader d = new BufferedReader(
new InputStreamReader(fstream));
while ((record = d.readLine()) != null) {
System.out.println(record);
}
d.close();
fstream.close();
} catch (Exception e) {
System.err.println("File input error");
}
}
/**
*
* 2006上午10:41:32
*/
void file() {
File file2 = new File("E://");
/* 列出目录下的所有文件 */
File[] file3 = file2.listFiles();
for (int i = 0, j = file3.length; i < j; i++) {
System.out.println("It ok!" + file3[i].getPath());
File file = new File(fileName);
/* 三种属性的获取 */
String fileName = file.getName();
String fileParent = file.getParent();
String filePath = file.getPath();
System.out.println("fileName:" + fileName + "/t" + fileParent
+ "/t" + filePath);
/* 判断是否存在该文件 */
if (!file.exists()) {
System.out.println("It isn't exist!");
}
try {
/* 如果不存在创建该文件 */
file.createNewFile();
boolean retValue = false;
retValue = file.isFile();
System.out.println("It ok!" + retValue);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}