package com.rdps.dev.fliu.server;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
/**
* File test class.
* @author frank
* @since 11/18/2010
* */
public class FileTest {
public static void main(String[] args){
String content = FileTest.readFile("/home/frank/Desktop/testfile");
System.out.println(content);
FileTest.writeFile("write test data into file.", "/home/frank/Desktop", "testfile");
}
/**
* Write the content to a file.
* */
public static boolean writeFile(String content, String path, String fileName){
File file = new File(path);
System.out.println("The file's location is:"+path+"/"+fileName);
try {
BufferedWriter bw = new BufferedWriter(new FileWriter(file+"/"+fileName,true));
bw.write(content);
bw.write(" ");
bw.flush();
bw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
}
/**
* Read content from a file.
* */
public static String readFile(String path){
StringBuilder content = new StringBuilder("");
File file = new File(path);
try {
FileInputStream fis = new FileInputStream(file);
byte[] bytearray = new byte[fis.available()];
int bytetotal = fis.available();
while(fis.read(bytearray,0,bytetotal)!=-1){
String temp = new String(bytearray,0,bytetotal);
content.append(temp);
}
} catch (FileNotFoundException e) {
System.out.println("frank's file not exits....");
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return content.toString();
}
}
转载于:https://www.cnblogs.com/frankliiu-java/archive/2010/11/18/1880556.html