洛阳北大青鸟:看JAVA是如何读写TXT文件的
有关Java如何读写txt文件这个问题经常在面试时会被问到,不懂或不熟悉的同志们可是要记好了哟!洛阳北大青鸟的李老师为大家解读:
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<="" i++)="">
output.write(String.valueOf(ResolveList.get(i)) + “\n”);
}
output.close();
} catch (Exception ex) {
System.out.println(ex);
}
}
}
综上大家明白了吗?希望对大家有所帮助。