📄 filechanneltester.java
字号:
import java.io.*;
import java.nio.*;
import java.nio.channels.*;
import java.nio.charset.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.io.File;
public class FileChannelTester {
public static void writeFile(String address,String str)throws IOException{
final int BSIZE=1024;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
String time = sdf.format(new Date()).toString();
//向文件中写数据
//FileChannel fc=new FileOutputStream("logs.txt").getChannel();
//FileChannel fc=new FileOutputStream("logs.txt").getChannel();
// fc.write(ByteBuffer.wrap("你好,".getBytes()));
// fc.close();
File file = new File(".\\logs");
if(!file.exists())file.mkdirs();
//向文件末尾添加数据
FileChannel fc=new RandomAccessFile(".\\logs\\logs.txt","rw").getChannel();
fc.position(fc.size()); //定位到文件末尾
if(null != str && !"".equals(str)){
str = time + ":" + address + ",请求的页面为 " + str + " 。\r\n\r\n";
} else {
str = time + ":" + address +" 。\r\n\r\n";
}
fc.write(ByteBuffer.wrap(str.getBytes()));
fc.close();
//读数据
//fc=new FileInputStream("D:\\logs.txt").getChannel();
fc=new FileInputStream(".\\logs\\logs.txt").getChannel();
ByteBuffer buff=ByteBuffer.allocate(BSIZE);
fc.read(buff); //把文件中的数据读入到ByteBuffer中
buff.flip();
Charset cs=Charset.defaultCharset(); //获得本地平台的字符编码
String str2 = cs.decode(buff).toString(); //转换为Unicode编码
System.out.println(str2);
fc.close();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -