Java Code Examples for java.io.RandomAccessFile#close()
The following examples show how to use
java.io.RandomAccessFile#close() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: HttpServerTest.java From msf4j with Apache License 2.0 | 8 votes |
@Test public void testChunkAggregatedUpload() throws IOException { //create a random file to be uploaded. int size = 69 * 1024; File fname = new File(tmpFolder, "testChunkAggregatedUpload.txt"); fname.createNewFile(); RandomAccessFile randf = new RandomAccessFile(fname, "rw"); randf.setLength(size); randf.close(); //test chunked upload HttpURLConnection urlConn = request("/test/v1/aggregate/upload", HttpMethod.PUT); urlConn.setChunkedStreamingMode(1024); Files.copy(Paths.get(fname.toURI()), urlConn.getOutputStream()); assertEquals(200, urlConn.getResponseCode()); assertEquals(size, Integer.parseInt(getContent(urlConn).split(":")[1].trim())); urlConn.disconnect(); fname.delete(); }
Example 2
Source File: JdpDoSomething.java From TencentKona-8 with GNU General Public License v2.0 | 6 votes |
public static void printJdpPacket(JdpJmxPacket p) { if (getVerbose()) { try { RandomAccessFile f = new RandomAccessFile("out.dmp", "rw"); f.write(p.getPacketData()); f.close(); } catch (IOException e) { System.out.println("Can't write a dump file: " + e); } System.out.println("Id: " + p.getId()); System.out.println("Jmx: " + p.getJmxServiceUrl()); System.out.println("Main: " + p.getMainClass()); System.out.println("InstanceName: " + p.getInstanceName()); System.out.println("ProccessId: " + p.getProcessId()); System.out.println("BroadcastInterval: " + p.getBroadcastInterval()); System.out.println("Rmi Hostname: " + p.getRmiHostname()); System.out.flush(); } }
Example 3
Source File: TrueTypeCollection.java From pentaho-reporting with GNU Lesser General Public License v2.1 | 6 votes |
public TrueTypeCollection( final File filename ) throws IOException { this.filename = filename; final RandomAccessFile raf = new RandomAccessFile( filename, "r" ); final byte[] headerBuffer = new byte[ 12 ]; raf.readFully( headerBuffer ); if ( ByteAccessUtilities.readULong( headerBuffer, 0 ) != MAGIC_NUMBER ) { raf.close(); throw new IOException(); } numFonts = ByteAccessUtilities.readLong( headerBuffer, 8 ); final byte[] offsetBuffer = new byte[ (int) ( 4 * numFonts ) ]; raf.readFully( offsetBuffer ); final int size = (int) numFonts; offsets = new long[ size ]; fonts = new TrueTypeFont[ size ]; for ( int i = 0; i < size; i++ ) { offsets[ i ] = ByteAccessUtilities.readULong( offsetBuffer, i * 4 ); } }
Example 4
Source File: RandomAccessFileDemo.java From Java with Artistic License 2.0 | 6 votes |
private static void write() throws IOException { // �������� RandomAccessFile raf = new RandomAccessFile("raf.txt", "rw"); // д���� raf.writeInt(100); raf.writeChar('a'); // raf.writeUTF("hello"); raf.writeUTF("����ϼ"); raf.seek(1000); raf.writeUTF("����"); // �ͷ���Դ raf.close(); }
Example 5
Source File: JdpDoSomething.java From jdk8u-jdk with GNU General Public License v2.0 | 6 votes |
public static void printJdpPacket(JdpJmxPacket p) { if (getVerbose()) { try { RandomAccessFile f = new RandomAccessFile("out.dmp", "rw"); f.write(p.getPacketData()); f.close(); } catch (IOException e) { System.out.println("Can't write a dump file: " + e); } System.out.println("Id: " + p.getId()); System.out.println("Jmx: " + p.getJmxServiceUrl()); System.out.println("Main: " + p.getMainClass()); System.out.println("InstanceName: " + p.getInstanceName()); System.out.println("ProccessId: " + p.getProcessId()); System.out.println("BroadcastInterval: " + p.getBroadcastInterval()); System.out.println("Rmi Hostname: " + p.getRmiHostname()); System.out.flush(); } }
Example 6
Source File: FileChange.java From Green-Creator with GNU General Public License v2.0 | 6 votes |
public FileChange(File file) throws IOException { if(!file.exists()) { System.out.println("File not found"); throw new IOException(); } this.file = file; RandomAccessFile rsf = new RandomAccessFile(this.file, "rw"); this.data = new byte[(int) rsf.length()]; rsf.read(data); int pos = 0; while (pos < data.length) { instBuf.add(data[pos++]); } rsf.close(); getLength(); }
Example 7
Source File: FileNioMapped.java From dble with GNU General Public License v2.0 | 6 votes |
FileNioMapped(String fileName, String mode) throws IOException { if ("r".equals(mode)) { this.mode = MapMode.READ_ONLY; } else { this.mode = MapMode.READ_WRITE; } this.name = fileName; logger.debug("create FileNioMapped :" + fileName); file = new RandomAccessFile(fileName, mode); try { reMap(); } catch (IOException e) { file.close(); file = null; throw e; } }
Example 8
Source File: ByteStore.java From COLA with GNU Lesser General Public License v2.1 | 6 votes |
private void saveDataFileHead(MockDataFile mockDataFile, File file) throws Exception { RandomAccessFile raf = new RandomAccessFile(file, "rw"); //将写文件指针移到文件尾。 raf.seek(raf.length()); raf.writeBytes("\r\n"); raf.writeBytes(Constants.RESPONSE_DATA_DELIMITER); raf.writeBytes("\r\n"); for (MockData mockData : mockDataFile.getAllMockData()) { raf.writeBytes(mockData.getDataId()+Constants.RESPONSE_METHOD_DELIMITER); raf.writeBytes(mockData.getStart()+","+mockData.getEnd()); raf.writeBytes("\r\n"); } raf.close(); }
Example 9
Source File: TestShareMemory2.java From feeyo-redisproxy with BSD 3-Clause "New" or "Revised" License | 5 votes |
public static void main(String[] args) throws Exception { RandomAccessFile f = new RandomAccessFile("/Users/zhuam/git/feeyo/feeyoredis/test.txt", "rw"); FileChannel fc = f.getChannel(); MappedByteBuffer buf = fc.map(FileChannel.MapMode.READ_WRITE, 0, fc.size()); while (buf.hasRemaining()) { System.out.print((char)buf.get()); } System.out.println(); fc.close(); f.close(); }
Example 10
Source File: StorageUtils.java From FireFiles with Apache License 2.0 | 5 votes |
@TargetApi(Build.VERSION_CODES.JELLY_BEAN) private long getSizeTotalRAM(boolean isTotal) { long sizeInBytes = 1000; MemoryInfo mi = new MemoryInfo(); activityManager.getMemoryInfo(mi); if(isTotal) { try { if(Utils.hasJellyBean()){ long totalMegs = mi.totalMem; sizeInBytes = totalMegs; } else{ RandomAccessFile reader = new RandomAccessFile("/proc/meminfo", "r"); String load = reader.readLine(); String[] totrm = load.split(" kB"); String[] trm = totrm[0].split(" "); sizeInBytes=Long.parseLong(trm[trm.length-1]); sizeInBytes=sizeInBytes*1024; reader.close(); } } catch (Exception e) { } } else{ long availableMegs = mi.availMem; sizeInBytes = availableMegs; } return sizeInBytes; }
Example 11
Source File: WaveFileWriter.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
@Override public int write(AudioInputStream stream, AudioFileFormat.Type fileType, File out) throws IOException { Objects.requireNonNull(stream); Objects.requireNonNull(fileType); Objects.requireNonNull(out); // throws IllegalArgumentException if not supported WaveFileFormat waveFileFormat = (WaveFileFormat)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 = writeWaveFile(stream, waveFileFormat, 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( waveFileFormat.getByteLength()== AudioSystem.NOT_SPECIFIED ) { int dataLength=bytesWritten-waveFileFormat.getHeaderSize(); int riffLength=dataLength + waveFileFormat.getHeaderSize() - 8; RandomAccessFile raf=new RandomAccessFile(out, "rw"); // skip RIFF magic raf.skipBytes(4); raf.writeInt(big2little( riffLength )); // skip WAVE magic, fmt_ magic, fmt_ length, fmt_ chunk, data magic raf.skipBytes(4+4+4+WaveFileFormat.getFmtChunkSize(waveFileFormat.getWaveType())+4); raf.writeInt(big2little( dataLength )); // that's all raf.close(); } return bytesWritten; }
Example 12
Source File: RandomAccessFileTest.java From j2objc with Apache License 2.0 | 5 votes |
/** * java.io.RandomAccessFile#readInt() */ public void test_readInt() throws IOException { // Test for method int java.io.RandomAccessFile.readInt() RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw"); raf.writeInt(Integer.MIN_VALUE); raf.seek(0); assertEquals("Incorrect int read/written", Integer.MIN_VALUE, raf .readInt()); raf.close(); }
Example 13
Source File: EncryptedFileDataSource.java From Telegram with GNU General Public License v2.0 | 5 votes |
@Override public long open(DataSpec dataSpec) throws EncryptedFileDataSourceException { try { uri = dataSpec.uri; File path = new File(dataSpec.uri.getPath()); String name = path.getName(); File keyPath = new File(FileLoader.getInternalCacheDir(), name + ".key"); RandomAccessFile keyFile = new RandomAccessFile(keyPath, "r"); keyFile.read(key); keyFile.read(iv); keyFile.close(); file = new RandomAccessFile(path, "r"); file.seek(dataSpec.position); fileOffset = (int) dataSpec.position; bytesRemaining = dataSpec.length == C.LENGTH_UNSET ? file.length() - dataSpec.position : dataSpec.length; if (bytesRemaining < 0) { throw new EOFException(); } } catch (IOException e) { throw new EncryptedFileDataSourceException(e); } opened = true; transferStarted(dataSpec); return bytesRemaining; }
Example 14
Source File: AuFileWriter.java From jdk8u60 with GNU General Public License v2.0 | 5 votes |
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; }
Example 15
Source File: FileBlob.java From Carbonado with Apache License 2.0 | 5 votes |
public void setLength(long length) throws PersistException { try { RandomAccessFile raf = new RandomAccessFile(mFile, "rw"); raf.setLength(length); raf.close(); } catch (IOException e) { throw new PersistException(e); } }
Example 16
Source File: LogFileFactory.java From mt-flume with Apache License 2.0 | 5 votes |
static LogFile.RandomReader getRandomReader(File file, @Nullable KeyProvider encryptionKeyProvider) throws IOException { RandomAccessFile logFile = new RandomAccessFile(file, "r"); try { File metaDataFile = Serialization.getMetaDataFile(file); // either this is a rr for a just created file or // the metadata file exists and as such it's V3 if(logFile.length() == 0L || metaDataFile.exists()) { return new LogFileV3.RandomReader(file, encryptionKeyProvider); } int version = logFile.readInt(); if(Serialization.VERSION_2 == version) { return new LogFileV2.RandomReader(file); } throw new IOException("File " + file + " has bad version " + Integer.toHexString(version)); } finally { if(logFile != null) { try { logFile.close(); } catch(IOException e) { LOGGER.warn("Unable to close " + file, e); } } } }
Example 17
Source File: Basic.java From hottub with GNU General Public License v2.0 | 4 votes |
public static void main(String[] args) throws Exception { show(nonExistantFile); if (nonExistantFile.exists()) fail(nonExistantFile, "exists"); show(rwFile); testFile(rwFile, true, 6); rwFile.delete(); if (rwFile.exists()) fail(rwFile, "could not delete"); show(roFile); testFile(roFile, false, 0); show(thisDir); if (!thisDir.exists()) fail(thisDir, "does not exist"); if (thisDir.isFile()) fail(thisDir, "is a file"); if (!thisDir.isDirectory()) fail(thisDir, "is not a directory"); if (!thisDir.canRead()) fail(thisDir, "is readable"); if (!thisDir.canWrite()) fail(thisDir, "is writeable"); String[] fs = thisDir.list(); if (fs == null) fail(thisDir, "list() returned null"); out.print(" [" + fs.length + "]"); for (int i = 0; i < fs.length; i++) out.print(" " + fs[i]); out.println(); if (fs.length == 0) fail(thisDir, "is empty"); if (!nonExistantFile.createNewFile()) fail(nonExistantFile, "could not create"); nonExistantFile.deleteOnExit(); if (!nonDir.mkdir()) fail(nonDir, "could not create"); if (!dir.renameTo(new File("x.Basic.dir2"))) fail(dir, "failed to rename"); if (System.getProperty("os.name").equals("SunOS") && System.getProperty("os.version").compareTo("5.6") >= 0) { if (bigFile.exists()) { bigFile.delete(); if (bigFile.exists()) fail(bigFile, "could not delete"); } RandomAccessFile raf = new RandomAccessFile(bigFile, "rw"); long big = ((long)Integer.MAX_VALUE) * 2; try { raf.seek(big); raf.write('x'); show(bigFile); testFile(bigFile, true, big + 1); } finally { raf.close(); } bigFile.delete(); if (bigFile.exists()) fail(bigFile, "could not delete"); } else { System.err.println("NOTE: Large files not supported on this system"); } }
Example 18
Source File: ARLDataInfo.java From MeteoInfo with GNU Lesser General Public License v3.0 | 4 votes |
@Override public GridData getGridData_LonLat(int timeIdx, String varName, int levelIdx) { try { int xNum, yNum; xNum = dataHead.NX; yNum = dataHead.NY; double[][] theData; RandomAccessFile br = new RandomAccessFile(this.getFileName(), "r"); byte[] dataBytes; DataLabel aDL; //Update level and variable index Variable aVar = this.getVariable(varName); if (aVar.getLevelNum() > 1) { levelIdx += 1; } int varIdx = LevelVarList.get(levelIdx).indexOf(aVar.getName()); br.seek(timeIdx * recsPerTime * recLen); br.seek(br.getFilePointer() + indexLen); for (int i = 0; i < levelIdx; i++) { br.seek(br.getFilePointer() + LevelVarList.get(i).size() * recLen); } br.seek(br.getFilePointer() + varIdx * recLen); //Read label aDL = ARLDataInfo.readDataLabel(br); //Read Data dataBytes = new byte[(int)recLen - 50]; br.read(dataBytes); br.close(); theData = unpackARLGridData(dataBytes, xNum, yNum, aDL); GridData gridData = new GridData(); gridData.data = theData; gridData.missingValue = missingValue; gridData.xArray = X; gridData.yArray = Y; return gridData; } catch (IOException ex) { Logger.getLogger(ARLDataInfo.class.getName()).log(Level.SEVERE, null, ex); return null; } }
Example 19
Source File: ARLDataInfo.java From MeteoInfo with GNU Lesser General Public License v3.0 | 4 votes |
@Override public GridData getGridData_TimeLat(int lonIdx, String varName, int levelIdx) { try { int xNum, yNum, tNum, t; xNum = dataHead.NX; yNum = dataHead.NY; tNum = this.getTimeNum(); double[][] theData; RandomAccessFile br = new RandomAccessFile(this.getFileName(), "r"); byte[] dataBytes; DataLabel aDL; double[][] newGridData = new double[tNum][yNum]; //Update level and variable index Variable aVar = this.getVariable(varName); if (aVar.getLevelNum() > 1) { levelIdx += 1; } int varIdx = LevelVarList.get(levelIdx).indexOf(aVar.getName()); for (t = 0; t < tNum; t++) { br.seek(t * recsPerTime * recLen); br.seek(br.getFilePointer() + indexLen); for (int i = 0; i < levelIdx; i++) { br.seek(br.getFilePointer() + LevelVarList.get(i).size() * recLen); } br.seek(br.getFilePointer() + varIdx * recLen); //Read label aDL = ARLDataInfo.readDataLabel(br); //Read Data dataBytes = new byte[(int)recLen - 50]; br.read(dataBytes); theData = unpackARLGridData(dataBytes, xNum, yNum, aDL); for (int i = 0; i < yNum; i++) { newGridData[t][i] = theData[i][lonIdx]; } } br.close(); GridData gridData = new GridData(); gridData.data = newGridData; gridData.missingValue = missingValue; gridData.xArray = Y; gridData.yArray = new double[tNum]; for (int i = 0; i < tNum; i++) { gridData.yArray[i] = JDateUtil.toOADate(this.getTimes().get(i)); } return gridData; } catch (IOException ex) { Logger.getLogger(ARLDataInfo.class.getName()).log(Level.SEVERE, null, ex); return null; } }
Example 20
Source File: MutilDownLoad.java From Android-Basics-Codes with Artistic License 2.0 | 4 votes |
/** * @param args */ public static void main(String[] args) { // (1). �����ͷ�������Դ�ļ�һ����С�Ŀ��ļ� try { // 1. ��ʼ��Url URL url = new URL(path); // 2. ͨ��Url��ȡHttp���� HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // 3. �����������������ʽ conn.setRequestMethod("GET"); // 4. ��ȡ������ 200:�ɹ� 3xxx���� 4xxx�ͻ��˴��� 500���������� int code = conn.getResponseCode(); // 5. �õ��ӷ������˷��ص���Դ�ļ��Ĵ�С int fileLength = conn.getContentLength(); if (code == 200) { System.out.println("��������Դ�ļ��Ĵ�С��" + fileLength); RandomAccessFile raf = new RandomAccessFile(getFileName(), "rw"); // ��Ҫ�����ļ��Ĵ�С raf.setLength(fileLength); raf.close(); } // (2).��������߳����� // ÿ������Ĵ�С int blockSize = fileLength / threadCount; for (int threadId = 0; threadId < threadCount; threadId++) { int startIndex = threadId * blockSize; int endIndex = (threadId + 1) * blockSize; // ���һ���߳� if (threadId == threadCount - 1) { // �����ļ�������λ�� endIndex = fileLength - 1; } // ��ʼ�߳� new DownLoadThread(startIndex, endIndex, threadId).start(); } } catch (Exception e) { e.printStackTrace(); } }