您的位置:首页 > 编程语言 > Java开发

Java读写txt文件

2009-11-16 12:41 531 查看
笔试的时候想不起来怎么写了。留个代码作纪念

package common;

import java.io.*;
import java.util.ArrayList;

public class IOTest {

public static void main (String args[]) {

ReadDate();

WriteDate();

}

/**
* 读取数据
*/
public static void ReadDate() {
String url = "e:/2.txt";
try {
FileReader read = new FileReader(new File(url));
StringBuffer sb = new StringBuffer();
char ch[] = new char[1024];
int d = read.read(ch);
while(d!=-1){
String str = new String(ch,0,d);
sb.append(str);
d = read.read(ch);
}
System.out.print(sb.toString());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

/**
* 写入数据
*/
public static void WriteDate() {

try{
File file = new File("D:/abc.txt");
if (file.exists()) {

file.delete();
}

file.createNewFile();

BufferedWriter output = new BufferedWriter(new FileWriter(file));

ArrayList ResolveList = new ArrayList();

for (int i = 0; i < 10; i++) {

ResolveList.add(Math.random()* 100);

}

for (int i=0 ;i<ResolveList.size(); i++) {
output.write(String.valueOf(ResolveList.get(i)) + "/n");
}
output.close();
} catch (Exception ex) {
System.out.println(ex);
}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: