标签:close cat fileread \n com print length finally import
文件的写入:
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("\r\n hello world 12123");
for (int i = 1; i < 1000; i++) {
writer.write("\t" + 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();
}
}
}
}
使用FileWriter把文件写入 ,使用 File Reader把文件读出 到控制台
标签:close cat fileread \n com print length finally import
原文地址:https://www.cnblogs.com/gyh520520/p/9373935.html