public classFileStream {public static voidmain(String[] args) {
FileStream fs= newFileStream();//String content =//fs.readFileWithInputStream("/home/rding/file/File1.txt");//System.out.println(content);
fs.writeFileWithOutputStream("/home/rding/file/File3.txt", "Hello File3");//fs.copyFile("/home/rding/file/File3.txt",//"/home/rding/file/File4.txt");
}public voidcopyFile(String srcPath, String descPath) {
InputStream inStream= null;
OutputStream outStream= null;try{
inStream= newFileInputStream(srcPath);
outStream= newFileOutputStream(descPath);int size =inStream.available();byte[] byteArr = new byte[size];
inStream.read(byteArr);
outStream.write(byteArr);
}catch(FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e) {
e.printStackTrace();
}
}public voidwriteFileWithOutputStream(String filePath, String content) {
OutputStream outStream= null;byte[] byteArr =content.getBytes();try{
//注意,outStream第一次建立后,就不会更新了,必须关闭再重新建立
outStream= newFileOutputStream(filePath);//outStream = new FileOutputStream(new File(filePath));
// 如果传入参数true,则接着原来文件后面继续写,而不是覆盖源文件。//outStream = new FileOutputStream(filePath, true);//outStream = new FileOutputStream(new File(filePath), true);
outStream.write(byteArr);
}catch(FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e) {
e.printStackTrace();
}finally{if (outStream != null) {try{
outStream.close();
}catch(IOException e) {
e.printStackTrace();
}
}
}
}publicString readFileWithInputStream(String filePath) {
InputStream inStream= null;
String result= "";try{
inStream= newFileInputStream(filePath);//inStream = new FileInputStream(new File(filePath));
int size =inStream.available();byte[] byteArr = new byte[size];
inStream.read(byteArr);
result= newString(byteArr);
}catch(FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e) {
e.printStackTrace();
}finally{if (inStream != null) {try{
inStream.close();
}catch(IOException e) {
e.printStackTrace();
}
}
}returnresult;
}
}