gwl4808306
【源码分享】自己扩展的File类的方法

扩展了两个方法,一个read()一个是appendText(),主要是appendText我觉得挺有用,新手手敲,大家给意见:)

[mw_shl_code=java,true]import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

public class FileExtend extends File {

private static final long serialVersionUID = -3641281297280978372L;

public FileExtend(String pathname) {

super(pathname);

}

/**

* 从文本文件中读取所有字符串

*

* @return 读取到的所有字符串

* @throws FileNotFoundException

*/

public String read() throws FileNotFoundException {

File file = new File(super.getPath());

if(!file.exists())throw new FileNotFoundException();

InputStream fis = null;

try {

fis = new FileInputStream(file);

int len = 0;

byte[] ch = new byte[(int) file.length()];

len = fis.read(ch);

return new String(ch, 0, len);

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

} finally {

try {

if (fis != null) {

fis.close();

}

} catch (IOException e) {

e.printStackTrace();

}

}

return null;

}

/**

* 追加给定字符串到指定文本文件中

*

* @param appendStr

* 待追加的字符串

*/

public void appendText(String appendStr) {

if (appendStr == null)

throw new NullPointerException();

if (appendStr.trim().length() == 0)

throw new IllegalArgumentException("Append string too short");

OutputStream fos = null;

String path = super.getPath();// 获得父类的变量值

try {

if (new File(path).exists()) {

String srcContent = read();// 获得文本文件的原内容

fos = new FileOutputStream(path);

String str = srcContent + appendStr;// 拼接出新的内容

byte[] bt = str.getBytes();

fos.write(bt);// 写入新内容

}

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

} finally {

if (fos != null) {

try {

fos.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

}

}

[/mw_shl_code]

gwl4808306
小野千帆
展开Biu

小野千帆 发表于 2012-8-24 14:24

好多try...catch......

我的话我会全部写在throws后面就不管了......

读取的话我一直用的thinking in java ...

是的,最好是想你这样写,BufferedReader读取文件的方法挺好的!我平常都按行读,懒:P

[查看全文]
不能吃的鸭子
小野千帆
本帖最后由
展开Biu

本帖最后由 小野千帆 于 2012-8-24 14:29 编辑

好多try...catch......

我的话我会全部写在throws后面就不管了......

读取的话我一直用的thinking in java里的代码:

[mw_shl_code=java,true]public class BufferedInputFile {

public static String read(String filename) throws IOException{

BufferedReader in=new BufferedReader(new FileReader(filename));

String s;

StringBuilder sb=new StringBuilder();

while((s=in.readLine())!=null){

sb.append(s);

}

in.close();

return sb.toString();

}

}[/mw_shl_code]

[查看全文]