Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/353.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
java FileChannel写入文件并在结尾添加\n_Java_File Io_File Processing_Filechannel - Fatal编程技术网

java FileChannel写入文件并在结尾添加\n

java FileChannel写入文件并在结尾添加\n,java,file-io,file-processing,filechannel,Java,File Io,File Processing,Filechannel,我正在尝试使用FileChannel创建日志。 由于某些原因,它无法获取文件中的\n字符 我的职能: private void serverLog(String status, String message) { currentTime = new Date().getTime(); String date = dateFormat.format(currentTime); String time = timeForm

我正在尝试使用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

您想要
\n
字符在哪里?当您记录两行时会发生什么?您可以在我的日志中看到我记录了两行,并且您可以看到在我的serverLog函数中,我在日志行的末尾\n尝试以下操作:公共静态最终字符串NEWLINE=System.getProperty(“line.separator”);如果(!file.exists())file.createNewFile(),则删除
:在下一行中创建RandomAccessFile已经完成了这项工作。不要在
tryLock()
中旋转:使用
lock()
并阻止,直到你得到它。你真的很难做到这一点。您可以使用新的FileWriter(xxx,true)将大部分内容附加到文件中。