本文整理汇总了Java中java.nio.channels.FileChannel.read方法的典型用法代码示例。如果您正苦于以下问题:Java FileChannel.read方法的具体用法?Java FileChannel.read怎么用?Java FileChannel.read使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类java.nio.channels.FileChannel
的用法示例。
在下文中一共展示了FileChannel.read方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: main
import java.nio.channels.FileChannel; //导入方法依赖的package包/类
public static void main(String[] args) throws IOException {
RandomAccessFile aFile = new RandomAccessFile("/Users/zhenpeng/aa.txt", "rw");
FileChannel inChannel = aFile.getChannel();
ByteBuffer buf = ByteBuffer.allocate(2);
int bytesRead = inChannel.read(buf);
while (bytesRead != -1) {
buf.flip();
while (buf.hasRemaining()) {
System.out.print((char) buf.get());
}
buf.clear();
//bytesRead = inChannel.read(buf);
//buf.putChar('f');
bytesRead = inChannel.read(buf);
}
aFile.close();
}
示例2: extractID3v2TagDataIntoFile
import java.nio.channels.FileChannel; //导入方法依赖的package包/类
/**
* Extracts the raw ID3v2 tag data into a file.
* <p/>
* This provides access to the raw data before manipulation, the data is written from the start of the file
* to the start of the Audio Data. This is primarily useful for manipulating corrupted tags that are not
* (fully) loaded using the standard methods.
*
* @param outputFile to write the data to
* @return
* @throws TagNotFoundException
* @throws IOException
*/
public File extractID3v2TagDataIntoFile(File outputFile) throws TagNotFoundException, IOException {
int startByte = (int) ((MP3AudioHeader) audioHeader).getMp3StartByte();
if (startByte >= 0) {
//Read byte into buffer
FileInputStream fis = new FileInputStream(file);
FileChannel fc = fis.getChannel();
ByteBuffer bb = ByteBuffer.allocate(startByte);
fc.read(bb);
//Write bytes to outputFile
FileOutputStream out = new FileOutputStream(outputFile);
out.write(bb.array());
out.close();
fc.close();
fis.close();
return outputFile;
}
throw new TagNotFoundException("There is no ID3v2Tag data in this file");
}
示例3: fileChannelExa
import java.nio.channels.FileChannel; //导入方法依赖的package包/类
/**
* FileChannel 负责文件的读写
* @throws IOException
*/
public void fileChannelExa() throws IOException {
String filePath = BasicChannelExample.class.getClassLoader().getResource("data/nio-data.txt").getFile();
RandomAccessFile aFile = new RandomAccessFile(filePath , "rw");
FileChannel inChannel = aFile.getChannel();
ByteBuffer buf = ByteBuffer.allocate(48);
int bytesRead = inChannel.read(buf);
while (bytesRead != -1) {
System.out.println("Read " + bytesRead);
buf.flip();
while(buf.hasRemaining()){
System.out.print((char) buf.get());
}
buf.clear();
bytesRead = inChannel.read(buf);
}
aFile.close();
}
示例4: readFile2BytesByChannel
import java.nio.channels.FileChannel; //导入方法依赖的package包/类
/**
* 读取文件到字节数组中
*
* @param file 文件
* @return 字符数组
*/
public static byte[] readFile2BytesByChannel(File file) {
if (!FileUtils.isFileExists(file)) return null;
FileChannel fc = null;
try {
fc = new RandomAccessFile(file, "r").getChannel();
ByteBuffer byteBuffer = ByteBuffer.allocate((int) fc.size());
while (true) {
if (!((fc.read(byteBuffer)) > 0)) break;
}
return byteBuffer.array();
} catch (IOException e) {
e.printStackTrace();
return null;
} finally {
CloseUtils.closeIO(fc);
}
}
示例5: getNextTokenSize
import java.nio.channels.FileChannel; //导入方法依赖的package包/类
public static long getNextTokenSize(FileChannel fileChannel, long position, byte[]... btsArr)
throws IOException {
long ret = -1;
ByteBuffer buffer = ByteBuffer.allocateDirect(8192);
if (position >= 0) {
fileChannel.position(position);
}
long startPosition = fileChannel.position();
outer:
while (fileChannel.read(buffer) != -1) {
buffer.flip();
int index;
while ((index = findBytes(buffer, btsArr)) != -1) {
ret = fileChannel.position() - startPosition - buffer.limit() + index;
break outer;
}
buffer.clear();
}
fileChannel.position(startPosition);
return ret;
}
示例6: preadHeader
import java.nio.channels.FileChannel; //导入方法依赖的package包/类
/**
* Read the header without changing the position of the FileChannel.
*
* @param fc The FileChannel to read.
* @return the Metadata Header.
* @throws IOException on error.
*/
public static BlockMetadataHeader preadHeader(FileChannel fc)
throws IOException {
final byte arr[] = new byte[getHeaderSize()];
ByteBuffer buf = ByteBuffer.wrap(arr);
while (buf.hasRemaining()) {
if (fc.read(buf, 0) <= 0) {
throw new EOFException("unexpected EOF while reading " +
"metadata file header");
}
}
short version = (short)((arr[0] << 8) | (arr[1] & 0xff));
DataChecksum dataChecksum = DataChecksum.newDataChecksum(arr, 2);
return new BlockMetadataHeader(version, dataChecksum);
}
示例7: findCentralDirStartOffset
import java.nio.channels.FileChannel; //导入方法依赖的package包/类
public static long findCentralDirStartOffset(final FileChannel fileChannel, final long commentLength) throws IOException {
// End of central directory record (EOCD)
// Offset Bytes Description[23]
// 0 4 End of central directory signature = 0x06054b50
// 4 2 Number of this disk
// 6 2 Disk where central directory starts
// 8 2 Number of central directory records on this disk
// 10 2 Total number of central directory records
// 12 4 Size of central directory (bytes)
// 16 4 Offset of start of central directory, relative to start of archive
// 20 2 Comment length (n)
// 22 n Comment
// For a zip with no archive comment, the
// end-of-central-directory record will be 22 bytes long, so
// we expect to find the EOCD marker 22 bytes from the end.
final ByteBuffer zipCentralDirectoryStart = ByteBuffer.allocate(4);
zipCentralDirectoryStart.order(ByteOrder.LITTLE_ENDIAN);
fileChannel.position(fileChannel.size() - commentLength - 6); // 6 = 2 (Comment length) + 4 (Offset of start of central directory, relative to start of archive)
fileChannel.read(zipCentralDirectoryStart);
final long centralDirStartOffset = zipCentralDirectoryStart.getInt(0);
return centralDirStartOffset;
}
示例8: deleteTagChunkUsingSmallByteBufferSegments
import java.nio.channels.FileChannel; //导入方法依赖的package包/类
/**
* Use ByteBuffers to copy a 4mb chunk, write the chunk and repeat until the rest of the file after the ID3 tag
* is rewritten
*
* @param existingTag existing tag
* @param channel channel
* @param newLength new length
* @param lengthTagChunk length tag chunk
* @throws IOException if something goes wrong
*/
// TODO: arguments are not used, position is implicit
private void deleteTagChunkUsingSmallByteBufferSegments(final AiffTag existingTag, final FileChannel channel, final long newLength, final long lengthTagChunk)
throws IOException {
final ByteBuffer buffer = ByteBuffer.allocateDirect((int) TagOptionSingleton.getInstance().getWriteChunkSize());
while (channel.read(buffer) >= 0 || buffer.position() != 0) {
buffer.flip();
final long readPosition = channel.position();
channel.position(readPosition - lengthTagChunk - buffer.limit());
channel.write(buffer);
channel.position(readPosition);
buffer.compact();
}
}
示例9: compute
import java.nio.channels.FileChannel; //导入方法依赖的package包/类
@Override protected void compute() {
try( FileInputStream s = new FileInputStream(new File(_path))) {
FileChannel fc = s.getChannel();
fc.position(_off);
fc.read(_bb=ByteBuffer.wrap(_chk));
} catch( Exception e) {
System.err.println("chunk: " + _cidx + "; bytesToRead: " + _chkSize +"; offset: " + _off);
throw new RuntimeException(e);
}
}
示例10: loadBaseAndCheckByFileChannel
import java.nio.channels.FileChannel; //导入方法依赖的package包/类
private boolean loadBaseAndCheckByFileChannel(String path) {
try {
FileInputStream fis = new FileInputStream(path);
// 1.从FileInputStream对象获取文件通道FileChannel
FileChannel channel = fis.getChannel();
int fileSize = (int) channel.size();
// 2.从通道读取文件内容
ByteBuffer byteBuffer = ByteBuffer.allocate(fileSize);
// channel.read(ByteBuffer) 方法就类似于 inputstream.read(byte)
// 每次read都将读取 allocate 个字节到ByteBuffer
channel.read(byteBuffer);
// 注意先调用flip方法反转Buffer,再从Buffer读取数据
byteBuffer.flip();
// 有几种方式可以操作ByteBuffer
// 可以将当前Buffer包含的字节数组全部读取出来
byte[] bytes = byteBuffer.array();
byteBuffer.clear();
// 关闭通道和文件流
channel.close();
fis.close();
int index = 0;
size = ByteUtil.bytesHighFirstToInt(bytes, index);
index += 4;
base = new int[size + 65535]; // 多留一些,防止越界
check = new int[size + 65535];
for (int i = 0; i < size; i++) {
base[i] = ByteUtil.bytesHighFirstToInt(bytes, index);
index += 4;
check[i] = ByteUtil.bytesHighFirstToInt(bytes, index);
index += 4;
}
} catch (Exception e) {
return false;
}
return true;
}
示例11: testAll
import java.nio.channels.FileChannel; //导入方法依赖的package包/类
@Test
void testAll() throws Exception {
initChannel("testAll");
assertFalse(s3channel.hasDelayedHeader());
assertEquals(0, s3channel.headerSize());
final FileChannel fc = FileChannel.open(file.path, StandardOpenOption.READ);
final ByteBuffer chunk = ByteBuffer.allocate(chunkSize);
int todo = (int) file.size;
while (todo >= chunkSize) {
chunk.rewind();
fc.read(chunk);
chunk.rewind();
assertEquals(chunkSize, s3channel.write(chunk));
todo -= chunkSize;
}
if (todo > 0) {
chunk.rewind();
chunk.limit(todo);
assertEquals(todo, fc.read(chunk));
assertEquals(fc.position(), fc.size());
chunk.rewind();
assertEquals(todo, s3channel.write(new ByteBuffer[] { chunk }));
}
// setting lower position does not make any effect
assertEquals(s3channel.position(s3channel.position() - 100).position(), s3channel.size());
fc.close();
s3channel.close();
assertFalse(s3channel.isOpen());
verifyFileContentEquality();
file.close();
}
示例12: readFileDataIntoBufferBE
import java.nio.channels.FileChannel; //导入方法依赖的package包/类
/**
*
* @param fc
* @param size
* @return
* @throws IOException
*/
public static ByteBuffer readFileDataIntoBufferBE(FileChannel fc, final int size) throws IOException
{
final ByteBuffer tagBuffer = ByteBuffer.allocateDirect(size);
fc.read(tagBuffer);
tagBuffer.position(0);
tagBuffer.order(ByteOrder.BIG_ENDIAN);
return tagBuffer;
}
示例13: readFully
import java.nio.channels.FileChannel; //导入方法依赖的package包/类
/**
* Reads as much as possible from the channel into the buffer.
*
* @param channel The channel.
* @param buffer The buffer.
* @param ptr The initial position in the channel.
* @throws IOException if an I/O error occurs.
*/
public static void readFully(FileChannel channel, ByteBuffer buffer, long ptr) throws IOException {
while (buffer.remaining() > 0) {
long read = channel.read(buffer, ptr);
if (read < -1) {
throw new EOFException();
} else {
ptr += read;
}
}
}
示例14: readFile
import java.nio.channels.FileChannel; //导入方法依赖的package包/类
@Override
public ResponseEntity<StreamingResponseBody> readFile(String fileLocation, String imageDir, String id,
String fileName) {
StreamingResponseBody streamingResponseBody = new StreamingResponseBody() {
@Override
public void writeTo(OutputStream outputStream) {
try {
String fileStr = fileLocation + File.separator + imageDir + File.separator + id + File.separator
+ fileName;
RandomAccessFile file = new RandomAccessFile(fileStr, "r");
FileChannel inChannel = file.getChannel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
while (inChannel.read(buffer) > 0) {
buffer.flip();
for (int i = 0; i < buffer.limit(); i++) {
outputStream.write(buffer.get());
}
buffer.clear();
outputStream.flush();
}
inChannel.close();
file.close();
} catch (IOException e) {
logger.error("Image Not Found : error " + e.getMessage());
throw new ResourceNotFoundException("Image Not Found : " + id + "/" + fileName);
}
}
};
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_TYPE, "image/*");
return new ResponseEntity<StreamingResponseBody>(streamingResponseBody, headers, HttpStatus.OK);
}
示例15: telnet
import java.nio.channels.FileChannel; //导入方法依赖的package包/类
public String telnet(Channel channel, String message) {
long size = 0 ;
File file = LoggerFactory.getFile();
StringBuffer buf = new StringBuffer();
if (message == null || message.trim().length() == 0) {
buf.append("EXAMPLE: log error / log 100");
}else {
String str[] = message.split(" ");
if (! StringUtils.isInteger(str[0])){
LoggerFactory.setLevel(Level.valueOf(message.toUpperCase()));
} else {
int SHOW_LOG_LENGTH = Integer.parseInt(str[0]);
if (file != null && file.exists()) {
try{
FileInputStream fis = new FileInputStream(file);
try {
FileChannel filechannel = fis.getChannel();
try {
size = filechannel.size();
ByteBuffer bb;
if (size <= SHOW_LOG_LENGTH) {
bb = ByteBuffer.allocate((int) size);
filechannel.read(bb, 0);
} else {
int pos = (int) (size - SHOW_LOG_LENGTH);
bb = ByteBuffer.allocate(SHOW_LOG_LENGTH);
filechannel.read(bb, pos);
}
bb.flip();
String content = new String(bb.array()).replace("<", "<")
.replace(">", ">").replace("\n", "<br/><br/>");
buf.append("\r\ncontent:"+content);
buf.append("\r\nmodified:"+(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
.format(new Date(file.lastModified()))));
buf.append("\r\nsize:"+size +"\r\n");
} finally {
filechannel.close();
}
} finally {
fis.close();
}
}catch (Exception e) {
buf.append(e.getMessage());
}
}else {
size = 0;
buf.append("\r\nMESSAGE: log file not exists or log appender is console .");
}
}
}
buf.append("\r\nCURRENT LOG LEVEL:"+ LoggerFactory.getLevel())
.append("\r\nCURRENT LOG APPENDER:"+ (file == null ? "console" : file.getAbsolutePath()));
return buf.toString();
}