1

我正在尝试使用 FileChannel 制作日志。由于某种原因,它没有在我的文件中获得 \n 字符。

我的功能:

private void serverLog(String status, String message)
    {           
        currentTime = new Date().getTime();
        String date = dateFormat.format(currentTime);
        String time = timeFormat.format(currentTime);
        String log = logFileName + date + "-" + time;
        String path = new File(".").getAbsolutePath();
        String logLine = date + "|" + time + "|" + status + "|" + message + "|" + Runtime.getRuntime().freeMemory() + "\n"; 
        File file = new File(path,log);

        try {
            if (!file.exists())                 
                file.createNewFile();
            fileChannel = new RandomAccessFile(file, "rw").getChannel();                
            FileLock lock = fileChannel.tryLock();

            while (!lock.isValid())
                lock = fileChannel.tryLock();

            if (lock.isValid())
            {
                fileChannel.position(fileChannel.size());
                ByteBuffer buf = ByteBuffer.allocate(logLine.length());
                buf.clear();
                buf.put(logLine.getBytes());
                buf.flip();
                while (buf.hasRemaining())
                    fileChannel.write(buf);     
                lock.release();
                fileChannel.close();
            }   

        } catch (FileNotFoundException e) {         
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }           
    }

这是我的输出文件:

16-05-2012|20-17-27|Success|New user connected: Id: 12345 Name: asaf IP: /0:0:0:0:0:0:0:1|8154448016-05-2012|20-17-27|Count|Current users online: 1, Current ghosts connections: 0|81544480
4

0 回答 0