下面列出了java.io.RandomAccessFile#length ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private void setDumpBuffer(RandomAccessFile file) throws IOException {
long length = file.length();
try {
if (length > Integer.MAX_VALUE) {
dumpBuffer = new LongMemoryMappedData(file, length, ENTRY_SIZE);
} else {
dumpBuffer = new MemoryMappedData(file, length);
}
} catch (IOException ex) {
if (ex.getCause() instanceof OutOfMemoryError) {
dumpBuffer = new FileData(file, length);
} else {
throw ex;
}
}
}
@Override
public long truncateFileAtURL(LocalFilesystemURL inputURL, long size) throws IOException {
File file = new File(filesystemPathForURL(inputURL));
if (!file.exists()) {
throw new FileNotFoundException("File at " + inputURL.URL + " does not exist.");
}
RandomAccessFile raf = new RandomAccessFile(filesystemPathForURL(inputURL), "rw");
try {
if (raf.length() >= size) {
FileChannel channel = raf.getChannel();
channel.truncate(size);
return size;
}
return raf.length();
} finally {
raf.close();
}
}
/**
* Corrupt the specified file. Some random bytes within the file
* will be changed to some random values.
*
* @throws IllegalArgumentException if the given file is not a file
* @throws IOException if an IOException occurs while reading or writing the file
*/
public static void corruptFile(File file) throws IOException {
if (!file.isFile()) {
throw new IllegalArgumentException(
"Given argument is not a file:" + file);
}
RandomAccessFile raf = new RandomAccessFile(file,"rws");
Random random = new Random();
for (long i = 0; i < raf.length(); i++) {
raf.seek(i);
if (random.nextBoolean()) {
raf.writeByte(random.nextInt());
}
}
raf.close();
}
private void passN() throws IOException
{
// Get FV from file
randomAccessFile = new RandomAccessFile(getCacheFile(), "r");
while (randomAccessFile.getFilePointer() < randomAccessFile.length())
{
int recordLength = (int) randomAccessFile.readLong();
packBuffer = growIfNeeded(packBuffer, recordLength);
randomAccessFile.read(packBuffer, 0, recordLength);
FeatureVector fv = toFeatureVector();
// add to ring buffer
addWithProb(fv);
}
randomAccessFile.close();
signalEndEpoch();
}
/**
* Check to see if a pattern matches the saved pattern. If no pattern
* exists, always returns true.
*
* @param pattern
* The pattern to check.
* @return Whether the pattern matches the stored one.
*/
public boolean checkPattern(List<LockPatternView.Cell> pattern) {
try {
// Read all the bytes from the file
RandomAccessFile raf = new RandomAccessFile(sLockPatternFilename,
"r");
final byte[] stored = new byte[(int) raf.length()];
int got = raf.read(stored, 0, stored.length);
raf.close();
if (got <= 0) {
return true;
}
// Compare the hash from the file with the entered pattern's hash
return Arrays.equals(stored,
LockPatternUtils.patternToHash(pattern));
} catch (FileNotFoundException fnfe) {
return true;
} catch (IOException ioe) {
return true;
}
}
private void transferLog(RandomAccessFile logFile, SocketChannel sChannel, int index) {
try {
long totalBytes = logFile.length();
System.out.println("---Called transferLog." + totalBytes + " " + (sChannel == null));
FileChannel fileChannel = logFile.getChannel();
long bytesTransfered = 0;
while (bytesTransfered < totalBytes) {
long bufferSize = 65536;
if (totalBytes - bytesTransfered < bufferSize) {
bufferSize = (int) (totalBytes - bytesTransfered);
if (bufferSize <= 0)
bufferSize = (int) totalBytes;
}
long bytesSent = fileChannel.transferTo(bytesTransfered, bufferSize, sChannel);
if (bytesSent > 0) {
bytesTransfered += bytesSent;
}
}
} catch (Exception e) {
e.printStackTrace();
System.err.println("State recover was aborted due to an unexpected exception");
}
}
public void channelActive(ChannelHandlerContext ctx) {
try {
File file=new File(filePath);
randomAccessFile = new RandomAccessFile(file, "r");
randomAccessFile.seek(0);
if ((randomAccessFile.length() % dataLength) == 0) {
sumCountpackage = (int) (randomAccessFile.length() / dataLength);
} else {
sumCountpackage = (int) (randomAccessFile.length() / dataLength) + 1;
}
byte[] bytes = new byte[dataLength];
LOGGER.debug("文件总长度:"+randomAccessFile.length());
if (randomAccessFile.read(bytes) != -1) {
EchoFile msgFile = new EchoFile();
msgFile.setSumCountPackage(sumCountpackage);
msgFile.setCountPackage(1);
msgFile.setBytes(bytes);
msgFile.setFile_md5(file.getName());
ctx.writeAndFlush(msgFile);
} else {
System.out.println("文件已经读完");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException i) {
i.printStackTrace();
}
}
public static void main(String... args) throws IOException {
String fileName = args[0];
long position = Integer.parseInt(args[1]);
String text = args[2];
RandomAccessFile file = new RandomAccessFile(fileName, "rw");
position = position > file.length() ? file.length() : position;
file.seek(position);
file.write(text.getBytes());
file.close();
}
private static void largeFile(String fileName) throws IOException {
if (!new File(fileName).exists()) {
System.out.println("not found: " + fileName);
return;
}
RandomAccessFile f = new RandomAccessFile(fileName, "r");
byte[] data = new byte[(int) f.length()];
f.readFully(data);
HashSet<Text> set = new HashSet<Text>(40 * 1024 * 1024);
int end = Text.indexOf(data, 0, '\n');
Text t = new Text(data, 0, end);
long time = System.currentTimeMillis();
while (true) {
set.add(t);
if (end >= data.length - 1) {
break;
}
int start = end + 1;
end = Text.indexOf(data, start, '\n');
t = new Text(data, start, end - start);
long now = System.currentTimeMillis();
if (now - time > 2000) {
System.out.println("size: " + set.size());
time = now;
}
}
System.out.println("file: " + fileName);
System.out.println("size: " + set.size());
test(set, 8, 14);
test(set, 8, 10);
test(set, 8, 16);
test(set, 8, 12);
}
/**
* 将表示此设备在该程序上的唯一标识符写入程序文件系统中。
*
* @param installation 保存唯一标识符的File对象。
* @return 唯一标识符。
* @throws java.io.IOException IO异常。
*/
private static String readInstallationFile(File installation) throws IOException {
RandomAccessFile accessFile = new RandomAccessFile(installation, "r");
byte[] bs = new byte[(int) accessFile.length()];
accessFile.readFully(bs);
accessFile.close();
return new String(bs);
}
private static void write_sector(RandomAccessFile f, int[] buf, int startOffset) throws IOException {
byte[] bytes = new byte[512];
ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN).asIntBuffer().put(buf, startOffset, 128);
if (Arrays.equals(bytes, MAGIC_TRIM_SECTOR)) {
if (f.length() > f.getFilePointer())
f.setLength(f.getFilePointer());
return;
}
f.write(bytes);
}
private static byte[] readFile(String fileName) throws IOException {
RandomAccessFile f = new RandomAccessFile(fileName, "r");
byte[] data = new byte[(int) f.length()];
f.readFully(data);
f.close();
return data;
}
public static boolean checkFileFormat(RandomAccessFile file)
throws IOException {
if (file.length() < Loader.MINIMUM_FILE_LENGTH)
return false;
byte[] magic = new byte[MAGIC_HEADER.length];
file.readFully(magic);
if (!Arrays.equals(MAGIC_HEADER, magic))
return false;
return true;
}
private static String readInstallationFile(File installation) throws IOException {
RandomAccessFile f = new RandomAccessFile(installation, "r");
byte[] bytes = new byte[(int) f.length()];
f.readFully(bytes);
f.close();
return new String(bytes);
}
/**
* 追加文件:使用RandomAccessFile
*/
public static 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();
}
}
public static boolean checkFileFormat(RandomAccessFile file)
throws IOException {
if (file.length() < Loader.MINIMUM_FILE_LENGTH)
return false;
byte[] magic = new byte[MAGIC_HEADER.length];
file.readFully(magic);
if (!Arrays.equals(MAGIC_HEADER, magic))
return false;
return true;
}
/**
* Returns the ZIP End of Central Directory record of the provided ZIP file.
*
* @return contents of the ZIP End of Central Directory record and the record's offset in the
* file or {@code null} if the file does not contain the record.
*
* @throws IOException if an I/O error occurs while reading the file.
*/
static Pair<ByteBuffer, Long> findZipEndOfCentralDirectoryRecord(RandomAccessFile zip)
throws IOException {
// ZIP End of Central Directory (EOCD) record is located at the very end of the ZIP archive.
// The record can be identified by its 4-byte signature/magic which is located at the very
// beginning of the record. A complication is that the record is variable-length because of
// the comment field.
// The algorithm for locating the ZIP EOCD record is as follows. We search backwards from
// end of the buffer for the EOCD record signature. Whenever we find a signature, we check
// the candidate record's comment length is such that the remainder of the record takes up
// exactly the remaining bytes in the buffer. The search is bounded because the maximum
// size of the comment field is 65535 bytes because the field is an unsigned 16-bit number.
long fileSize = zip.length();
if (fileSize < ZIP_EOCD_REC_MIN_SIZE) {
return null;
}
// Optimization: 99.99% of APKs have a zero-length comment field in the EoCD record and thus
// the EoCD record offset is known in advance. Try that offset first to avoid unnecessarily
// reading more data.
Pair<ByteBuffer, Long> result = findZipEndOfCentralDirectoryRecord(zip, 0);
if (result != null) {
return result;
}
// EoCD does not start where we expected it to. Perhaps it contains a non-empty comment
// field. Expand the search. The maximum size of the comment field in EoCD is 65535 because
// the comment length field is an unsigned 16-bit number.
return findZipEndOfCentralDirectoryRecord(zip, UINT16_MAX_VALUE);
}
public int write(AudioInputStream stream, AudioFileFormat.Type fileType, File out) throws IOException {
// throws IllegalArgumentException if not supported
AuFileFormat auFileFormat = (AuFileFormat)getAudioFileFormat(fileType, stream);
// first write the file without worrying about length fields
FileOutputStream fos = new FileOutputStream( out ); // throws IOException
BufferedOutputStream bos = new BufferedOutputStream( fos, bisBufferSize );
int bytesWritten = writeAuFile(stream, auFileFormat, bos );
bos.close();
// now, if length fields were not specified, calculate them,
// open as a random access file, write the appropriate fields,
// close again....
if( auFileFormat.getByteLength()== AudioSystem.NOT_SPECIFIED ) {
// $$kk: 10.22.99: jan: please either implement this or throw an exception!
// $$fb: 2001-07-13: done. Fixes Bug 4479981
RandomAccessFile raf=new RandomAccessFile(out, "rw");
if (raf.length()<=0x7FFFFFFFl) {
// skip AU magic and data offset field
raf.skipBytes(8);
raf.writeInt(bytesWritten-AuFileFormat.AU_HEADERSIZE);
// that's all
}
raf.close();
}
return bytesWritten;
}
private void openLogFile() {
try {
logWriter = new RandomAccessFile( this.logFile, "rw" );
logFileSize = logWriter.length();
logWriter.seek( logFileSize );
} catch (Exception e) {
logWriter = null;
}
}
public ZipInput( String filename) throws IOException
{
this.inputFilename = filename;
in = new RandomAccessFile( new File( inputFilename), "r");
fileLength = in.length();
}