/// <exception cref="System.IO.IOException"></exception> private void DoOpen() { try { if (invalid) { throw new PackInvalidException(packFile); } lock (readLock) { fd = new RandomAccessFile(packFile, "r"); length = fd.Length(); OnOpenPack(); } } catch (IOException ioe) { OpenFail(); throw; } catch (RuntimeException re) { OpenFail(); throw; } catch (Error re) { OpenFail(); throw; } }
/// <exception cref="Db4objects.Db4o.Ext.Db4oIOException"></exception> public FileBin(BinConfiguration config) { bool ok = false; try { _path = new Sharpen.IO.File(config.Uri()).GetCanonicalPath(); _file = RandomAccessFileFactory.NewRandomAccessFile(_path, config.ReadOnly(), config .LockFile()); if (config.InitialLength() > 0) { Write(config.InitialLength() - 1, new byte[] { 0 }, 1); } ok = true; } catch (IOException e) { throw new Db4oIOException(e); } finally { if (!ok) { Close(); } } }
public void ReadFromStorageTest() { IStorage storage = new RandomAccessFile(File.Open("ReadFromStorage", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None)); int size = 8; byte[] data = new byte[] { byte.MaxValue, byte.MinValue }; ReadFromStorageTestAssert(storage, size, data); int size2 = 1000000; byte[] data2 = new byte[] { }; ReadFromStorageTestAssert(storage, size2, data2); try { ReadFromStorageTestAssert(storage, -1, data2); Assert.Fail("Should throw exception"); } catch (InvalidUserHeaderException) { } int size3 = 10; byte[] data3 = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }; ReadFromStorageTestAssert(storage, size3, data3); storage.Close(); }
public RealtyManager(DatabaseInterface dbInterface) { DbInterface = dbInterface; var byNameFile = new FilePaths { FileBlockData = "../../../SystemCore/data/ByNameAndReg/blocks.txt", FileOverflowFile = "../../../SystemCore/data/ByNameAndReg/overflow.txt", FileTreeData = "../../../SystemCore/data/ByNameAndReg/configuration.txt" }; DhRealtyByNameAndRegNumber = new DynHash <RealtyByCadAndRegNumber>(byNameFile, DefaultBlockFactor, DefaultOverflowBlockFactor); var byId = new FilePaths { FileBlockData = "../../../SystemCore/data/ById/blocks.txt", FileOverflowFile = "../../../SystemCore/data/ById/overflow.txt", FileTreeData = "../../../SystemCore/data/ById/configuration.txt" }; DhRealtyById = new DynHash <RealtyById>(byId, DefaultBlockFactor, DefaultOverflowBlockFactor); var rafBlockFile = "../../../SystemCore/data/Raf/blocks.txt"; var rafConfFile = "../../../SystemCore/data/Raf/configuration.txt"; RafRealties = new RandomAccessFile <Realty>(rafBlockFile, rafConfFile, DefaultBlockFactor); }
public static byte[] readFile(Java.IO.File file) { // Open file RandomAccessFile f = new RandomAccessFile(file, "r"); try { // Get and check length long longlength = f.Length(); int length = (int)longlength; if (length != longlength) { throw new Java.IO.IOException("Tamanho do arquivo excede o permitido!"); } // Read file and return data byte[] data = new byte[length]; f.ReadFully(data); return(data); } catch (Exception ex) { System.Diagnostics.Debug.Write(ex); return(new byte[0]); } finally { f.Close(); } }
/// <exception cref="Db4objects.Db4o.Ext.Db4oIOException"></exception> protected RandomAccessFileAdapter(string path, bool lockFile, long initialLength, bool readOnly) { var ok = false; try { _path = new File(path).GetCanonicalPath(); _delegate = RandomAccessFileFactory.NewRandomAccessFile(_path, readOnly, lockFile ); if (initialLength > 0) { _delegate.Seek(initialLength - 1); _delegate.Write(new byte[] { 0 }); } ok = true; } catch (IOException e) { throw new Db4oIOException(e); } finally { if (!ok) { Close(); } } }
public static RandomAccessFile NewRandomAccessFile(String path, bool readOnly, bool lockFile) { RandomAccessFile raf = null; bool ok = false; try { raf = new RandomAccessFile(path, readOnly, lockFile); if (lockFile) { Platform4.LockFile(path, raf); } ok = true; return(raf); } catch (IOException x) { if (new File(path).Exists()) { throw new DatabaseFileLockedException(path, x); } throw new Db4oIOException(x); } finally { if (!ok && raf != null) { raf.Close(); } } }
public AnnTask(Context activity, int task, int annoMode, int curPos, long startPos, long endPos, int curWidth, int splitLineIndex, List <List <object> > lines, List <object> curLine, string pastedText, long textLen, RandomAccessFile openedFile, LineView testView, IAnnTask inter, bool formatting, List <Bookmark> bookmarks) : base() { this.status = Status.Running; this.Activity = activity; this.task = task; this.annoMode = annoMode; this.curPos = curPos; this.startPos = startPos; this.endPos = endPos; this.curWidth = curWidth; this.splitLineIndex = splitLineIndex; this.lines = lines; this.curLine = curLine; this.PastedText = pastedText; this.textLen = textLen; this.OpenedFile = openedFile; TestView = testView; this.inter = inter; Formatting = formatting; this.Bookmarks = bookmarks; this.FoundBookmarks = new List <Bookmark>(); curFilePos = -1; Scheduler = TaskScheduler.FromCurrentSynchronizationContext(); UpdateVars(activity); }
public static byte[] readFile(File file) { // Open file var f = new RandomAccessFile(file, "r"); try { // Get and check length long longlength = f.Length(); var length = (int)longlength; if (length != longlength) { throw new IOException("Filesize exceeds allowed size"); } // Read file and return data byte[] data = new byte[length]; f.ReadFully(data); return(data); } catch (Exception ex) { System.Diagnostics.Debug.Write(ex); return(new byte[0]); } finally { f.Close(); } }
/// <summary> /// Calculate the md5sum of an image after zeroing out the transaction ID /// field in the header. /// </summary> /// <remarks> /// Calculate the md5sum of an image after zeroing out the transaction ID /// field in the header. This is useful for tests that want to verify /// that two checkpoints have identical namespaces. /// </remarks> /// <exception cref="System.IO.IOException"/> public static string GetImageFileMD5IgnoringTxId(FilePath imageFile) { FilePath tmpFile = FilePath.CreateTempFile("hadoop_imagefile_tmp", "fsimage"); tmpFile.DeleteOnExit(); try { Files.Copy(imageFile, tmpFile); RandomAccessFile raf = new RandomAccessFile(tmpFile, "rw"); try { raf.Seek(ImageTxidPos); raf.WriteLong(0); } finally { IOUtils.CloseStream(raf); } return(GetFileMD5(tmpFile)); } finally { tmpFile.Delete(); } }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: //ORIGINAL LINE: public static void truncateFile(java.io.File file, long position) throws java.io.IOException public static void TruncateFile(File file, long position) { using (RandomAccessFile access = new RandomAccessFile(file, "rw")) { TruncateFile(access.Channel, position); } }
public void Annotate(string filePath) { File fileFd = new File(filePath); try { openedFile = new RandomAccessFile(fileFd, "r"); textLen = Convert.ToInt32(fileFd.Length()); if (annoMode != ANNOTATE_FILE) { sharedPrefs.Edit().PutString("lastText", pastedText).Commit(); } annoMode = ANNOTATE_FILE; curFilePath = filePath; curSaveName = Regex.Replace(fileFd.Name, @"(\.[^.]*)$", "_ChineseReader"); Title = fileFd.Name; Annotate(-1); } catch (Exception e) { Toast.MakeText(Application, e.Message, ToastLength.Long).Show(); } }
//public static void WriteHexDumpFromFile(string filename) //{ // try // { // File file = new File(filename); // RandomAccessFile stream = new RandomAccessFile(file, "r"); // sbyte[] bytes = new sbyte[stream.length()]; // stream.read(bytes); // stream.close(); // System.Console.WriteLine("dump of [" + file + "]"); // Console.WriteHexDump(bytes); // } // catch (Exception exc) // { // Console.WriteThrowable(exc); // } //} /// <summary> /// writes bytes to file /// </summary> /// <param name="cdata"></param> /// <param name="p"></param> public static void WriteBytes(sbyte[] cdata, string filename, bool utf8) { try { File f = new File(filename); if (f.exists()) { f.delete(); } RandomAccessFile stream = new RandomAccessFile(filename, "rw"); if (utf8) { stream.writeByte(0xEF); stream.writeByte(0xBB); stream.writeByte(0xBF); } stream.write(cdata); stream.close(); } catch { } }
private void @lock() { RandomAccessFile randomAccessFile = new RandomAccessFile(PooledBatchManager.lockFile, "rw"); this._lock = randomAccessFile.getChannel().@lock(); randomAccessFile.close(); }
private void btn_RAF_Click(object sender, EventArgs e) { //updates the random access file to the currently selected layout RandomAccessFile.UpdateRafFile(root.Layout); try { //search for the student string cellData = RandomAccessFile.FindRecord(Convert.ToInt32(tb_search.Text)); student = MainWindowController.FindStudent(root, cellData); UpdateStudentList(cellData); //gets all the information about the student Layout layout = MainWindowController.FindStudent(root, cellData); //highlight the cell of the student dgv_class.CurrentCell = dgv_class.Rows[layout.Vertical].Cells[layout.Horizontal]; } catch (Exception) { if (string.IsNullOrWhiteSpace(tb_search.Text)) { MessageBox.Show("Please enter a record number and try again.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); } else { //name has to match and if not show message MessageBox.Show("There is no student at that record number, please try again.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } }
private static void LogToFile(string msg) { if (enabled) { if (!writeToLogFile) { return; } lock (Lock) { if (_logFile == null) { try { _logFile = new RandomAccessFile(LogFile(), "rw"); LogToFile("\r\n\r\n ********** BEGIN LOG ********** \r\n\r\n "); } catch (IOException e) { Sharpen.Runtime.PrintStackTrace(e); } } msg = DateHandlerBase.Now() + "\r\n" + msg + "\r\n"; byte[] bytes = stringIO.Write(msg); try { _logFile.Write(bytes); } catch (IOException e) { Sharpen.Runtime.PrintStackTrace(e); } } } }
/// <summary> /// Create a row-oriented reader from an input stream. /// </summary> public static ParquetRowReader <TTuple> CreateRowReader <TTuple>(RandomAccessFile randomAccessFile) { var fields = GetFieldsAndProperties(typeof(TTuple)); var readDelegate = GetOrCreateReadDelegate <TTuple>(fields); return(new ParquetRowReader <TTuple>(randomAccessFile, readDelegate, fields)); }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @SuppressWarnings("deprecation") public void testDummy() throws Exception public virtual void TestDummy() { File = new File(CreateTempDir("leftover"), "child.locked"); OpenFile = new RandomAccessFile(File, "rw"); Parent = LuceneTestCase.BaseTempDirForTestClass; }
public RafTester() { var rafBlockFile = "C:/Users/janik/source/repos/US_SemestralnaPraca2/StructureTester/testData/rafBlocks.txt"; var rafConfFile = "C:/Users/janik/source/repos/US_SemestralnaPraca2/StructureTester/testData/rafConf.txt"; TestRaf = new RandomAccessFile <TestRecord>(rafBlockFile, rafConfFile, 10); InsertedNumbers = new List <RafTestBock>(); }
/// <summary>Read the header at the beginning of the given block meta file.</summary> /// <remarks> /// Read the header at the beginning of the given block meta file. /// The current file position will be altered by this method. /// If an error occurs, the file is <em>not</em> closed. /// </remarks> /// <exception cref="System.IO.IOException"/> public static Org.Apache.Hadoop.Hdfs.Server.Datanode.BlockMetadataHeader ReadHeader (RandomAccessFile raf) { byte[] buf = new byte[GetHeaderSize()]; raf.Seek(0); raf.ReadFully(buf, 0, buf.Length); return(ReadHeader(new DataInputStream(new ByteArrayInputStream(buf)))); }
/** Parse the sdsd box in an mp4 file * fis: proper mp4 file * pos: stsd box's position in the file */ public StsdBox(RandomAccessFile fis, long pos) { this.fis = fis; this.pos = pos; findBoxAvcc(); findSPSandPPS(); }
// https://stackoverflow.com/questions/16963292/read-current-cpu-frequency/19858957#19858957 float GetFrequency(string path) { using (var reader = new RandomAccessFile(path, "r")) { float.TryParse(reader.ReadLine(), out var result); return(result / 1000); } }
public IndexFile(int id, RandomAccessFile data, RandomAccessFile index, byte[] readCacheBuffer, bool newProtocol) { _id = id; _data = data; _index = index; _newProtocol = newProtocol; _readCacheBuffer = readCacheBuffer; }
public ParquetFileReader(RandomAccessFile randomAccessFile) { if (randomAccessFile == null) { throw new ArgumentNullException(nameof(randomAccessFile)); } _handle = new ParquetHandle(ExceptionInfo.Return <IntPtr>(randomAccessFile.Handle, ParquetFileReader_Open), ParquetFileReader_Free); }
/// <exception cref="System.IO.IOException"/> public virtual void Corrupt(FilePath editFile) { // Corrupt the last edit long fileLen = editFile.Length(); RandomAccessFile rwf = new RandomAccessFile(editFile, "rw"); rwf.SetLength(fileLen - 1); rwf.Close(); }
/// <summary> /// Initialize a filestream from and input and/or output stream. /// </summary> private FileStream(RandomAccessFile file, FileAccess access) { if (file == null) { throw new ArgumentNullException("file"); } this.file = file; this.access = access; }
/// <exception cref="System.IO.IOException"></exception> public virtual void TestReadOnlyLocked() { byte[] bytes = new byte[1]; RandomAccessFile raf = RandomAccessFileFactory.NewRandomAccessFile(TempFile(), true , true); Assert.Expect(typeof(IOException), new _ICodeBlock_43(raf, bytes)); raf.Close(); }
/// <exception cref="System.IO.IOException"></exception> private byte[] ReadAllBytes(string fileName) { var length = (int) new Sharpen.IO.File(fileName).Length(); var raf = new RandomAccessFile(fileName, "rw"); var buffer = new byte[length]; raf.Read(buffer); raf.Close(); return buffer; }
private static long GetTotalMemory() { using (var reader = new RandomAccessFile("/proc/meminfo", "r")) { var line = reader.ReadLine(); // first line --> MemTotal: xxxxxx kB var split = line.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); return(Convert.ToInt64(split[1]) * 1024); } }
//private static String readInstallationFile(File installation) //{ // RandomAccessFile f = new RandomAccessFile(installation, "r"); // byte[] bytes = new byte[(int)f.Length()]; // f.ReadFully(bytes); // f.Close(); // return new Java.Lang.String(bytes).ToString(); //} private static String readInstallationFile(Java.IO.File installation) { RandomAccessFile f = new RandomAccessFile(installation, "r"); byte[] bytes = new byte[(int)f.Length()]; f.ReadFully(bytes); f.Close(); return(new Java.Lang.String(bytes).ToString()); }
/// <exception cref="System.IO.IOException"/> public RandomAccessFileReader([NotNull] RandomAccessFile file) { if (file == null) { throw new ArgumentNullException(); } _file = file; _length = _file.Length(); }
private static void LogToFile(string msg) { if (enabled) { if (!writeToLogFile) { return; } lock (Lock) { if (_logFile == null) { try { _logFile = new RandomAccessFile(LogFile(), "rw"); LogToFile("\r\n\r\n ********** BEGIN LOG ********** \r\n\r\n "); } catch (IOException e) { Runtime.PrintStackTrace(e); } } msg = DateHandlerBase.Now() + "\r\n" + msg + "\r\n"; var bytes = stringIO.Write(msg); try { _logFile.Write(bytes); } catch (IOException e) { Runtime.PrintStackTrace(e); } } } }
/// <summary> /// Open a random access file for the given path, more and access. /// </summary> private static RandomAccessFile Open(string path, FileMode mode, FileAccess access) { var file = new Java.Io.File(path); switch (mode) { case FileMode.CreateNew: if (file.Exists()) throw new IOException("File already exists"); break; case FileMode.Open: if (!file.Exists()) throw new FileNotFoundException(path); break; case FileMode.Append: access = FileAccess.Write; break; } switch (mode) { case FileMode.Create: case FileMode.CreateNew: case FileMode.OpenOrCreate: if (access == FileAccess.Read) { //create empty file, so it can be opened again with read only right, //otherwise an FilNotFoundException is thrown. var additinalAccessFile = new RandomAccessFile(file, "rw"); } break; } var jMode = (access == FileAccess.Read) ? "r" : "rw"; var randomAccessFile = new RandomAccessFile(file, jMode); switch (mode) { case FileMode.Truncate: randomAccessFile.SetLength(0); break; case FileMode.Append: randomAccessFile.Seek(randomAccessFile.Length()); break; } return randomAccessFile; }
private void FinishHeader() { try { lock (_randomAccessLock) { if (_randomAccessWriter == null) return; _randomAccessWriter.Seek(4); // Write size to RIFF header _randomAccessWriter.WriteInt(Integer.ReverseBytes(36 + _payloadSize)); _randomAccessWriter.Seek(40); // Write size to Subchunk2Size field _randomAccessWriter.WriteInt(Integer.ReverseBytes(_payloadSize)); _randomAccessWriter.Close(); _randomAccessWriter.Dispose(); _randomAccessWriter = null; } } catch (IOException e) { Log.Error(Tag, "I/O exception occured while closing output file " + e.Message + e.StackTrace); State = WavRecorderState.Error; } }
public void Release() { Log.Debug(Tag, "before release recorder"); if (IsRecording) { Log.Error(Tag, "Release(): Tried to Release running WavRecorder. Please stop the recoder before release."); throw new IllegalStateException(); } try { lock (_randomAccessLock) { if (_randomAccessWriter != null) { _randomAccessWriter.Close(); _randomAccessWriter.Dispose(); _randomAccessWriter = null; } } } catch (IOException e) { Log.Error(Tag, "Release(): I/O exception occured while closing output file" + e.Message + e.StackTrace); } //if(File.Exists(_filePath)) File.Delete(_filePath); if (_audioRecord != null) { _audioRecord.Stop(); _audioRecord.Release(); _audioRecord.Dispose(); _audioRecord = null; } Log.Debug(Tag, "after release recorder"); }
private void InitializeHeader() { try { lock (_randomAccessLock) { _randomAccessWriter = new RandomAccessFile(_filePath, "rw"); _randomAccessWriter.SetLength(0); // Set file length to 0, to prevent unexpected behavior in case the file already existed _randomAccessWriter.WriteBytes("RIFF"); _randomAccessWriter.WriteInt(0); // Final file size not known yet, write 0 _randomAccessWriter.WriteBytes("WAVE"); _randomAccessWriter.WriteBytes("fmt "); _randomAccessWriter.WriteInt(Integer.ReverseBytes(16)); // Sub-chunk size, 16 for PCM _randomAccessWriter.WriteShort(Short.ReverseBytes(1)); // AudioFormat, 1 for PCM _randomAccessWriter.WriteShort(Short.ReverseBytes(Channels)); // Number of channels, 1 for mono, 2 for stereo _randomAccessWriter.WriteInt(Integer.ReverseBytes(_sampleRate)); // Sample rate _randomAccessWriter.WriteInt(Integer.ReverseBytes(_sampleRate * FmtAvgBps * Channels / 8)); // Byte rate, SampleRate*NumberOfChannels*BitsPerSample/8 _randomAccessWriter.WriteShort(Short.ReverseBytes(Channels * FmtAvgBps / 8)); // Block align, NumberOfChannels*BitsPerSample/8 _randomAccessWriter.WriteShort(Short.ReverseBytes(FmtAvgBps)); // Bits per sample _randomAccessWriter.WriteBytes("data"); _randomAccessWriter.WriteInt(0); // Data chunk size not known yet, write 0 } } catch (NullReferenceException e) { Log.Debug(Tag, e.Message + e.StackTrace); State = WavRecorderState.Error; } }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @SuppressWarnings("deprecation") public void testDummy() throws Exception public virtual void TestDummy() { File = new File(CreateTempDir("leftover"), "child.locked"); OpenFile = new RandomAccessFile(File, "rw"); Parent = LuceneTestCase.BaseTempDirForTestClass; }
//public void Reset() //{ // try // { // if (HasError) // { // Log.Debug(Tag, "Recorder was in Error state while reset."); // return; // } // Log.Debug(Tag, "before reset recorder"); // Release(); // _filePath = null; // //_audioRecord = new AudioRecord(AudioSource.Mic, _sampleRate, ChannelIn.Mono, Encoding.Pcm16bit, _bufferSize); // //State = WavRecorderState.Initializing; // InitializeAudioRecord(_sampleRate); // Log.Debug(Tag, "after reset recorder"); // } // catch (Exception e) // { // Log.Error(Tag, e.Message); // State = WavRecorderState.Error; // } //} public void Release() { Log.Debug(Tag, "before release recorder"); if (IsRecording) { Stop(); } else if (IsReady) { try { lock (_randomAccessLock) { if (_randomAccessWriter != null) { _randomAccessWriter.Close(); _randomAccessWriter = null; } } } catch (IOException e) { Log.Error(Tag, "I/O exception occured while closing output file" + e.Message); } File.Delete(_filePath); } if (_audioRecord != null) { _audioRecord.Release(); _audioRecord = null; } Log.Debug(Tag, "after release recorder"); }
private static long GetTotalMemory() { using (var reader = new RandomAccessFile("/proc/meminfo", "r")) { var line = reader.ReadLine(); // first line --> MemTotal: xxxxxx kB var split = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); return Convert.ToInt64(split[1]) * 1024; } }
/// <exception cref="System.IO.IOException"></exception> public virtual int WriteVersions(string file, bool writeTrash) { var count = 0; var rcount = 0; var lastFileName = file + "0"; var rightFileName = file + "R"; File4.Copy(lastFileName, rightFileName); var syncIter = _writes.GetEnumerator(); while (syncIter.MoveNext()) { rcount++; var writesBetweenSync = (Collection4) syncIter.Current; var rightRaf = new RandomAccessFile(rightFileName, "rw"); var singleForwardIter = writesBetweenSync.GetEnumerator(); while (singleForwardIter.MoveNext()) { var csw = (CrashSimulatingWrite) singleForwardIter.Current; csw.Write(rightFileName, rightRaf, false); } rightRaf.Close(); var singleBackwardIter = writesBetweenSync.GetEnumerator(); while (singleBackwardIter.MoveNext()) { count++; var csw = (CrashSimulatingWrite) singleBackwardIter.Current; var currentFileName = file + "W" + count; File4.Copy(lastFileName, currentFileName); var raf = new RandomAccessFile(currentFileName, "rw"); csw.Write(currentFileName, raf, writeTrash); raf.Close(); lastFileName = currentFileName; } File4.Copy(rightFileName, rightFileName + rcount); lastFileName = rightFileName; } return count; }
/// <summary> /// Initialize a filestream from and input and/or output stream. /// </summary> private FileStream(RandomAccessFile file, FileAccess access) { if (file == null) throw new ArgumentNullException("file"); this.file = file; this.access = access; }