ConcurrentDiskUtil
public class ConcurrentDiskUtil {
/**
* get file content.
*
* @param path file path
* @param charsetName charsetName
* @return content
* @throws IOException IOException
*/
public static String getFileContent(String path, String charsetName) throws IOException {
File file = new File(path);
return getFileContent(file, charsetName);
}
/**
* get file content.
*
* @param file file
* @param charsetName charsetName
* @return content
* @throws IOException IOException
*/
public static String getFileContent(File file, String charsetName) throws IOException {
RandomAccessFile fis = null;
FileLock rlock = null;
try {
fis = new RandomAccessFile(file, "r");
FileChannel fcin = fis.getChannel();
int i = 0;
do {
try {
rlock = fcin.tryLock(0L, Long.MAX_VALUE, true);
} catch (Exception e) {
++i;
if (i > RETRY_COUNT) {
LOGGER.error("read {} fail;retryed time:{}", file.getName(), i);
throw new IOException("read " + file.getAbsolutePath() + " conflict");
}
sleep(SLEEP_BASETIME * i);
LOGGER.warn("read {} conflict;retry time:{}", file.getName(), i);
}
} while (null == rlock);
int fileSize = (int) fcin.size();
ByteBuffer byteBuffer = ByteBuffer.allocate(fileSize);
fcin.read(byteBuffer);
byteBuffer.flip();
return byteBufferToString(byteBuffer, charsetName);
} finally {
if (rlock != null) {
rlock.release();
rlock = null;
}
if (fis != null) {
fis.close();
fis = null;
}
}
}
/**
* write file content.
*
* @param path file path
* @param content content
* @param charsetName charsetName
* @return whether write ok
* @throws IOException IOException
*/
public static Boolean writeFileContent(String path, String content, String charsetName) throws IOException {
File file = new File(path);
return writeFileContent(file, content, charsetName);
}
/**
* write file content.
*
* @param file file
* @param content content
* @param charsetName charsetName
* @return whether write ok
* @throws IOException IOException
*/
public static Boolean writeFileContent(File file, String content, String charsetName) throws IOException {
if (!file.exists()) {
boolean isCreateOk = file.createNewFile();
if (!isCreateOk) {
return false;
}
}
FileChannel channel = null;
FileLock lock = null;
RandomAccessFile raf = null;
try {
raf = new RandomAccessFile(file, "rw");
channel = raf.getChannel();
int i = 0;
do {
try {
lock = channel.tryLock();
} catch (Exception e) {
++i;
if (i > RETRY_COUNT) {
LOGGER.error("write {} fail;retryed time:{}", file.getName(), i);
throw new IOException("write " + file.getAbsolutePath() + " conflict");
}
sleep(SLEEP_BASETIME * i);
LOGGER.warn("write {} conflict;retry time:{}", file.getName(), i);
}
} while (null == lock);
ByteBuffer sendBuffer = ByteBuffer.wrap(content.getBytes(charsetName));
while (sendBuffer.hasRemaining()) {
channel.write(sendBuffer);
}
channel.truncate(content.length());
} catch (FileNotFoundException e) {
throw new IOException("file not exist");
} finally {
if (lock != null) {
try {
lock.release();
lock = null;
} catch (IOException e) {
LOGGER.warn("close wrong", e);
}
}
if (channel != null) {
try {
channel.close();
channel = null;
} catch (IOException e) {
LOGGER.warn("close wrong", e);
}
}
if (raf != null) {
try {
raf.close();
raf = null;
} catch (IOException e) {
LOGGER.warn("close wrong", e);
}
}
}
return true;
}
/**
* transfer ByteBuffer to String.
*
* @param buffer buffer
* @param charsetName charsetName
* @return String
* @throws IOException IOException
*/
public static String byteBufferToString(ByteBuffer buffer, String charsetName) throws IOException {
Charset charset = null;
CharsetDecoder decoder = null;
CharBuffer charBuffer = null;
charset = Charset.forName(charsetName);
decoder = charset.newDecoder();
charBuffer = decoder.decode(buffer.asReadOnlyBuffer());
return charBuffer.toString();
}
private static void sleep(int time) {
try {
Thread.sleep(time);
} catch (InterruptedException e) {
LOGGER.warn("sleep wrong", e);
}
}
private static final Logger LOGGER = LoggerFactory.getLogger(ConcurrentDiskUtil.class);
static final int RETRY_COUNT = 10;
/**
* ms.
*/
static final int SLEEP_BASETIME = 10;
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Is Eclipse IDE dying?In 2014 the Eclipse IDE is the leading development environment for Java with a market share of approximately 65%. but ac...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.