文件的写入:
package cn.hjh.com;
import java.io.FileWriter;
import java.io.IOException;
public class FileWriterDemo {
public static void main(String[] args) {
FileWriter writer = null;
try {
writer = new FileWriter("d:\hello.txt", true);//路径
// writer.write("
hello world 12123");
for (int i = 1; i < 1000; i++) {
writer.write(" " + i);
}
System.out.print("结束");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (writer != null)
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
文件的读出
package cn.hjh.com;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class FileReaderDemo {
public static void main(String[] args) throws IOException {
FileReader reader = null;
try {
reader = new FileReader("d:\hello.txt");
char[] buffer = new char[3];
/*while (true) {
int length = reader.read(buffer);
if (length == -1) {
break;
} else {
System.out.print(new String(buffer, 0, length));
}
}*/
int len=-1;
while ((len=reader.read(buffer))!=-1) {
System.out.print(new String(buffer, 0, len));//这部分用的挺多
}
System.out.println("================");
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (reader != null) {
reader.close();
}
}
}
}