扩展了两个方法,一个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]
crazy_lock 发表于 2012-9-17 17:49弱弱地说(不是打击,,,),,,
FileWrite的构造函数就有一个是否追加内容的参数,....(估计FileOutputStream也有 ...
[mw_shl_code=java,true] fis = new FileInputStream(file);
int len = 0;
byte[] ch = new byte[(int) file.length()];
len = fis.read(ch);
return new String(ch, 0, len);[/mw_shl_code]
说的是这个?
.......很同意你的说法 java数组没长度限制的吧 还是Interger.MAX_VALUE-1???
[查看全文]
弱弱地说(不是打击,,,),,,
FileWrite的构造函数就有一个是否追加内容的参数,....(估计FileOutputStream也有...?还是多查查api吧,,)
例如 PrintWriter pw = new PrintWriter(new FileWriter(serverFile, true));
再弱弱地说,如果文件有几个G大,那你一次性读取文件,就会造成内存溢满,导致程序崩溃.....所以一直都不存在该方法...(即使window下的文件映射也是部分读..)
加上java 的gc不定期(有时真的很久都不运行一次!!!)运行,你读取在内存中的内存(而且还有一个匿名类!!)...导致整个程序都不稳定..
那个读取指定长度的,,,,,,
其实可以用RandomAccessFile的,,,,多线程下载就是用这个IO的,,,,
[查看全文]
本帖最后由 gwl4808306 于 2012-8-25 00:29 编辑
再传一个:)见笑了
[mw_shl_code=java,true]/**
* 读取指定字节长度的文本
* @param byteLen 字节长度
* @return
*/
public String read(int byteLen ) throws FileNotFoundException,IOException {
InputStream fis=null;
String path=super.getPath();
fis=new FileInputStream(path);
byte[] b=new byte[byteLen];
int len=0;
len=fis.read(b);
if(fis!=null){
fis.close();
}
return new String(b,0,len);
}[/mw_shl_code]
[查看全文]
