⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 log.java

📁 这里是一个构建简单web服务器的部分java代码2
💻 JAVA
字号:


import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Log {
	public void writelog(String ip, int port, int count) {
		Date date = new Date();
		try {
			InetAddress address = InetAddress.getByName(ip);

			System.out.println("Connection " + count + ":connected to "
					+ address.getHostName() + " on port " + port + ".");
			String content = "Connection " + count + ":connected to " + address.getHostName()
					+ " on port " + port + ",";			
			String fileName = "./log.txt";
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String logcontent = content + df.format(date).toString();
			appendMethodA(fileName, logcontent);
			appendMethodA(fileName, "\n\r");
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/* 使用RandomAccessFile方法追加文件 */
	private void appendMethodA(String fileName, String content) {
		try {
			// 打开一个随机访问文件流,按读写方式
			RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw");
			// 文件长度,字节数
			long fileLength = randomFile.length();
			// 将写文件指针移到文件尾。
			randomFile.seek(fileLength);
			randomFile.writeBytes(content);
			randomFile.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -