java写文件中并发和乱码问题解决

时间:2022-04-02 13:36:50

文件最后一行加文字

public static void writeOneLine(String append,String category,String fileName){
FileChannel channel = null;
FileLock lock = null;
String path=FileOpearte.class.getResource("").toString();//文件相对路径的问题
path=path.substring(6, path.length()-5)+"data"+"//"+category+"//"+fileName;
File file=new File(path);
try {


if(!file.exists())
{

file.createNewFile();

}

RandomAccessFile rf=new RandomAccessFile(path,"rw");

channel = rf.getChannel();
//文件进程锁,当文件锁不可用时,当前进程会被挂起
//无参lock()默认为独占锁,不会报NonReadableChannelException异常,因为独占就是为了写
lock = channel.lock();


//将指针移动到文件末尾
rf.seek(rf.length());
//设置编码
append = new String(append.getBytes("utf-8"),"ISO8859_1");
rf.writeBytes(append+"\r\n"); //字符串末尾需要换行符
//释放锁
lock.release();
lock = null;
channel.close();
channel = null;
rf.close();//关闭文件流
}catch (IOException e){
e.printStackTrace();
}finally {
if (lock != null) {
try {
lock.release();
lock = null;
} catch (IOException e) {
e.printStackTrace();
}
}

if (channel != null) {
try {
channel.close();
channel = null;
} catch (IOException e) {
e.printStackTrace();
}
}

}
}