文件读取:
[Java] 纯文本查看 复制代码 import java.io.FileInputStream;
import java.io.IOException;
/**
* 读取文件例子
*/
public class FileInputDemo {
public static void main(String[] args) throws IOException {
System.out.println("demo");
FileInputStream fis = new FileInputStream("test.txt");
//读取test.txt内容并输出
int len;
byte[] buffer = new byte[1024];
while ((len = fis.read(buffer)) != -1) {
System.out.println(new String(buffer, 0, len));
}
fis.close();
System.out.println("ok");
}
}
写出文件:
[Java] 纯文本查看 复制代码 import java.io.FileOutputStream;
import java.io.IOException;
/**
* 写出文件例子
*/
public class FileOutputDemo {
public static void main(String[] args) throws IOException {
System.out.println("demo");
FileOutputStream fos = new FileOutputStream("test.txt");
String str = "hello 世界";
fos.write(str.getBytes());
fos.close();
System.out.println("ok");
}
}
读入文本文件内容:
[Java] 纯文本查看 复制代码 import java.io.FileReader;
import java.io.IOException;
/**
* 读取文本文件内容
*/
public class FileReaderDemo {
public static void main(String[] args) throws IOException {
FileReader fr = new FileReader("test.txt");
int len = 0;
//读取文本文件内容
char[] buf = new char[1024];
while ((len = fr.read(buf)) != -1) {
//输出
System.out.print(new String(buf, 0, len));
}
fr.close();
System.out.println("ok");
}
}
写出文本文件内容:
[Java] 纯文本查看 复制代码 import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* 写出文本文件内容
*/
public class FileWriterDemo {
public static void main(String[] args) throws IOException {
FileWriter fw = new FileWriter("test.txt");
//先清空原有内容在写入
fw.write("你好世界,翻译为英文是 Hello World");
//换行
fw.write("\r\n");
//获取当前时间
String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
//继续追加内容
fw.write(format);
fw.close();
System.out.println("ok");
}
}
|