Java Code Examples for java.io.RandomAccessFile.write()

The following are Jave code examples for showing how to use write() of the java.io.RandomAccessFile class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: proxyee-down   File: ByteUtil.java   Source Code and License Vote up 7 votes
public static void insertContent(String path, long offset, byte[] content) throws IOException {
  RandomAccessFile sourceRaf = new RandomAccessFile(path, "rw");
  File tempFile = FileUtil.createFile(path + ".tmp");
  RandomAccessFile tempRaf = new RandomAccessFile(tempFile, "rw");
  long fileSize = sourceRaf.length();
  FileChannel sourceChannel = sourceRaf.getChannel();
  FileChannel targetChannel = tempRaf.getChannel();
  long remaining = fileSize - offset;
  long position = offset;
  while (remaining > 0) {
    long transferred = sourceChannel.transferTo(position, remaining, targetChannel);
    remaining -= transferred;
    position += transferred;
  }
  sourceChannel.truncate(offset);
  sourceRaf.seek(offset);
  sourceRaf.write(content);
  long newOffset = sourceRaf.getFilePointer();
  targetChannel.position(0);
  sourceChannel.transferFrom(targetChannel, newOffset, (fileSize - offset));
  sourceChannel.close();
  targetChannel.close();
  FileUtil.deleteIfExists(tempFile);
}
 
Example 2
Project: flume-release-1.7.0   File: TestFileChannelRestart.java   Source Code and License Vote up 6 votes
@Test
public void testCorruptCheckpointCompleteMarkerMostSignificant4Bytes() throws Exception {
  Map<String, String> overrides = Maps.newHashMap();
  channel = createFileChannel(overrides);
  channel.start();
  Assert.assertTrue(channel.isOpen());
  Set<String> in = putEvents(channel, "restart", 10, 100);
  Assert.assertEquals(100, in.size());
  forceCheckpoint(channel);
  channel.stop();
  File checkpoint = new File(checkpointDir, "checkpoint");
  RandomAccessFile writer = new RandomAccessFile(checkpoint, "rw");
  writer.seek(EventQueueBackingStoreFile.INDEX_CHECKPOINT_MARKER *
              Serialization.SIZE_OF_LONG);
  writer.write(new byte[] { (byte) 1, (byte) 5 });
  writer.getFD().sync();
  writer.close();
  channel = createFileChannel(overrides);
  channel.start();
  Assert.assertTrue(channel.isOpen());
  Set<String> out = consumeChannel(channel);
  Assert.assertTrue(channel.didFullReplayDueToBadCheckpointException());
  compareInputAndOut(in, out);
}
 
Example 3
Project: hadoop   File: MiniDFSCluster.java   Source Code and License Vote up 6 votes
public static boolean corruptBlock(File blockFile) throws IOException {
  if (blockFile == null || !blockFile.exists()) {
    return false;
  }
  // Corrupt replica by writing random bytes into replica
  Random random = new Random();
  RandomAccessFile raFile = new RandomAccessFile(blockFile, "rw");
  FileChannel channel = raFile.getChannel();
  String badString = "BADBAD";
  int rand = random.nextInt((int)channel.size()/2);
  raFile.seek(rand);
  raFile.write(badString.getBytes());
  raFile.close();
  LOG.warn("Corrupting the block " + blockFile);
  return true;
}
 
Example 4
Project: oneKey2Alarm   File: aid.java   Source Code and License Vote up 6 votes
public void writeTxtToFile(String strcontent, String filePath, String fileName) {
    // �����ļ���֮���������ļ�����Ȼ�����
    makeFilePath(filePath, fileName);
	 
    String strFilePath = filePath + fileName;
    // ÿ��д��ʱ��������д
    String strContent = strcontent + "\r\n";
    try {
        File file = new File(strFilePath);
        if (!file.exists()) {
            Log.d("TestFile", "Create the file:" + strFilePath);
            file.getParentFile().mkdirs();
            file.createNewFile();
        }
        RandomAccessFile raf = new RandomAccessFile(file, "rwd");
        raf.seek(file.length());
        raf.write(strContent.getBytes());
        raf.close();
	 
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 5
Project: flume-release-1.7.0   File: EventQueueBackingStoreFile.java   Source Code and License Vote up 5 votes
protected static void allocate(File file, long totalBytes) throws IOException {
  RandomAccessFile checkpointFile = new RandomAccessFile(file, "rw");
  boolean success = false;
  try {
    if (totalBytes <= MAX_ALLOC_BUFFER_SIZE) {
      /*
       * totalBytes <= MAX_ALLOC_BUFFER_SIZE, so this can be cast to int
       * without a problem.
       */
      checkpointFile.write(new byte[(int) totalBytes]);
    } else {
      byte[] initBuffer = new byte[MAX_ALLOC_BUFFER_SIZE];
      long remainingBytes = totalBytes;
      while (remainingBytes >= MAX_ALLOC_BUFFER_SIZE) {
        checkpointFile.write(initBuffer);
        remainingBytes -= MAX_ALLOC_BUFFER_SIZE;
      }
      /*
       * At this point, remainingBytes is < MAX_ALLOC_BUFFER_SIZE,
       * so casting to int is fine.
       */
      if (remainingBytes > 0) {
        checkpointFile.write(initBuffer, 0, (int) remainingBytes);
      }
    }
    success = true;
  } finally {
    try {
      checkpointFile.close();
    } catch (IOException e) {
      if (success) {
        throw e;
      }
    }
  }
}
 
Example 6
Project: ru.olegsvs.mediatek_mac_changer   File: MacTools.java   Source Code and License Vote up 5 votes
private void writeNewMAC(String str) throws IOException {
    File fl = new File(MainPage.dataPath);
    RandomAccessFile raf = new RandomAccessFile(fl, "rw");
    try {
        raf.seek(4); // offset = 4 ( Начало MAC )
        raf.write(hexStringToByteArray(str)); // Пишем байты из hexString в файл
    } finally {
        raf.close(); // flush + close
    }
}
 
Example 7
Project: hadoop-oss   File: TestDU.java   Source Code and License Vote up 5 votes
private void createFile(File newFile, int size) throws IOException {
  // write random data so that filesystems with compression enabled (e.g., ZFS)
  // can't compress the file
  Random random = new Random();
  byte[] data = new byte[size];
  random.nextBytes(data);

  newFile.createNewFile();
  RandomAccessFile file = new RandomAccessFile(newFile, "rws");

  file.write(data);
    
  file.getFD().sync();
  file.close();
}
 
Example 8
Project: hadoop   File: TestNameNodeRecovery.java   Source Code and License Vote up 5 votes
@Override
public void corrupt(File editFile) throws IOException {
  // Add junk to the end of the file
  RandomAccessFile rwf = new RandomAccessFile(editFile, "rw");
  rwf.seek(editFile.length());
  rwf.write((byte)-1);
  for (int i = 0; i < 1024; i++) {
    rwf.write(padByte);
  }
  rwf.close();
}
 
Example 9
Project: Tarski   File: Util.java   Source Code and License Vote up 5 votes
/** Copy file.content[from...f.length-1] into file.content[to...], then truncate the file after that point.
 * <p> If (from &gt; to), this means we simply delete the portion of the file beginning at "to" and up to but excluding "from".
 * <p> If (from &lt; to), this means we insert (to-from) number of ARBITRARY bytes into the "from" location
 *     and shift the original file content accordingly.
 * <p> Note: after this operation, the file's current position will be moved to the start of the file.
 * @throws IOException if (from &lt; 0) || (to &lt; 0) || (from &gt;= file.length())
 */
public static void shift (RandomAccessFile file, long from, long to) throws IOException {
   long total = file.length();
   if (from<0 || from>=total || to<0) throw new IOException(); else if (from==to) {file.seek(0); return;}
   final byte buf[] = new byte[4096];
   int res;
   if (from>to) {
      while(true) {
         file.seek(from);
         if ((res=file.read(buf)) <= 0) { file.setLength(to); file.seek(0); return; }
         file.seek(to); file.write(buf, 0, res); from=from+res; to=to+res;
      }
   } else {
      file.seek(total);
      for(long todo=to-from; todo>0;) {
         if (todo >= buf.length) {file.write(buf); todo = todo - buf.length;} else {file.write(buf, 0, (int)todo); break;}
      }
      for(long todo=total-from; todo>0; total=total-res, todo=todo-res) {
         if (todo > buf.length) res=buf.length; else res=(int)todo;
         file.seek(total - res);
         for(int done=0; done<res;) { int r=file.read(buf, done, res-done); if (r<=0) throw new IOException(); else done += r; }
         file.seek(total - res + (to - from));
         file.write(buf, 0, res);
      }
   }
   file.seek(0);
}
 
Example 10
Project: LuaViewPlayground   File: ScriptBundleUltimateLoadTask.java   Source Code and License Vote up 5 votes
/**
 * save file
 *
 * @param destFile
 * @param fileData
 */
private void saveFileUsingRandomAccessFile(File destFile, byte[] fileData) {
    try {
        RandomAccessFile randomAccessFile = new RandomAccessFile(destFile, "rw");
        randomAccessFile.write(fileData);
        randomAccessFile.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 11
Project: DAA_Converter   File: DAA_Writer.java   Source Code and License Vote up 5 votes
private synchronized void writeByteInFile(byte[] b, long pos) {
	try {
		RandomAccessFile raf = new RandomAccessFile(out, "rw");
		try {
			raf.seek(pos);
			raf.write(b);
		} finally {
			raf.close();
		}
	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example 12
Project: openaudible   File: AbstractLyrics3v2FieldFrameBody.java   Source Code and License Vote up 5 votes
/**
 * Write the contents of this datatype to the file at the position it is
 * currently at.
 *
 * @param file destination file
 * @throws IOException on any I/O error
 */
public void write(RandomAccessFile file) throws IOException {
    //Write the various fields to file in order
    byte[] buffer;
    AbstractDataType object;
    Iterator<AbstractDataType> iterator = objectList.listIterator();
    while (iterator.hasNext()) {
        object = iterator.next();
        buffer = object.writeByteArray();
        file.write(buffer);
    }
}
 
Example 13
Project: MetadataEditor   File: FieldFrameBodyLYR.java   Source Code and License Vote up 5 votes
/**
 * @param file
 * @throws java.io.IOException
 */
public void write(RandomAccessFile file) throws java.io.IOException
{
    int size;
    int offset = 0;
    byte[] buffer = new byte[5];
    String str;

    size = getSize();
    str = Integer.toString(size);

    for (int i = 0; i < (5 - str.length()); i++)
    {
        buffer[i] = (byte) '0';
    }

    offset += (5 - str.length());

    for (int i = 0; i < str.length(); i++)
    {
        buffer[i + offset] = (byte) str.charAt(i);
    }

    offset += str.length();
    file.write(buffer, 0, 5);

    if (size > 0)
    {
        str = writeString();
        buffer = new byte[str.length()];

        for (int i = 0; i < str.length(); i++)
        {
            buffer[i] = (byte) str.charAt(i);
        }

        file.write(buffer);
    }
}
 
Example 14
Project: ZooKeeper   File: CRCTest.java   Source Code and License Vote up 5 votes
/**
 * corrupt a file by writing m at 500 b
 * offset
 * @param file the file to be corrupted
 * @throws IOException
 */
private void corruptFile(File file) throws IOException {
    // corrupt the logfile
    RandomAccessFile raf  = new RandomAccessFile(file, "rw");
    byte[] b = "mahadev".getBytes();
    long writeLen = 500L;
    raf.seek(writeLen);
    //corrupting the data
    raf.write(b);
    raf.close();
}
 
Example 15
Project: MetadataEditor   File: AbstractLyrics3v2FieldFrameBody.java   Source Code and License Vote up 5 votes
/**
 * Write the contents of this datatype to the file at the position it is
 * currently at.
 *
 * @param file destination file
 * @throws IOException on any I/O error
 */
public void write(RandomAccessFile file) throws IOException
{
    //Write the various fields to file in order
    byte[] buffer;
    AbstractDataType object;
    Iterator<AbstractDataType> iterator = objectList.listIterator();
    while (iterator.hasNext())
    {
        object = iterator.next();
        buffer = object.writeByteArray();
        file.write(buffer);
    }
}
 
Example 16
Project: org.alloytools.alloy   File: ByteBuffer.java   Source Code and License Vote up 5 votes
/**
 * Write the entire content into the given file using Flate compression (see
 * RFC1951) then return the number of bytes written.
 */
public long dumpFlate(RandomAccessFile os) throws IOException {
	Deflater zip = new Deflater(Deflater.BEST_COMPRESSION);
	byte[] output = new byte[8192];
	Iterator<byte[]> it = list.iterator(); // when null, that means we have
											// told the Deflater that no
											// more input would be coming
	long ans = 0; // the number of bytes written out so far
	while (true) {
		if (it != null && zip.needsInput() && it.hasNext()) {
			byte[] in = it.next();
			if (in == list.getLast()) {
				zip.setInput(in, 0, n);
				it = null;
				zip.finish();
			} else {
				zip.setInput(in, 0, SIZE);
			}
		}
		if (it == null && zip.finished())
			break;
		int count = zip.deflate(output);
		if (count > 0) {
			ans = ans + count;
			if (ans < 0)
				throw new IOException("Data too large to be written to the output file.");
			os.write(output, 0, count);
		}
	}
	return ans;
}
 
Example 17
Project: GitHub   File: DownloadTask.java   Source Code and License Vote up 4 votes
/**
 * 开始下载
 *
 * @param response 应答
 */
private void _onDownload(Response response) throws Throwable {
    InputStream inputStream = null;
    final RandomAccessFile accessFile = FileUtils.getRandomAccessFile(
            mFileInfo.getPath() + mFileInfo.getName() + ".tmp",
            mFileInfo.getLoadBytes(), mFileInfo.getTotalBytes());
    int loadBytes = mFileInfo.getLoadBytes();
    try {
        // 1.获取数据流
        inputStream = response.body().byteStream();
        BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream, BUFFER_SIZE);
        byte[] buff = new byte[BUFFER_SIZE];
        do {
            // 2.读数据
            int byteCount = bufferedInputStream.read(buff);
            if (byteCount == -1) {
                break;
            }
            // 3.写文件
            accessFile.write(buff, 0, byteCount);
            // 4.累加下载量
            loadBytes += byteCount;

            // 5.检测文件是否被其他操作
            if (accessFile.length() < loadBytes) {
                mIsRunning = false;
                throw new RuntimeException(
                        FileUtils.formatString("the file was changed by others when" +
                                " downloading. %d %d", accessFile.length(), loadBytes));
            } else {
                mFileInfo.setLoadBytes(loadBytes);
                _onProcess();
            }

            // 6.检测停止状态
            if (mIsCancel || mIsStop) {
                // callback on paused
                mIsRunning = false;
                if (mIsCancel) {
                    mListener.onCancel(mFileInfo);
                } else {
                    mListener.onStop(mFileInfo);
                }
                _updateDb();
                return;
            }
        } while (mIsRunning);

        // 7.处理 transfer encoding = chunked 的情况
        if (mFileInfo.getTotalBytes() == -1) {
            mFileInfo.setTotalBytes(loadBytes);
        }

        // 8.判断下载成功还是失败
        if (mFileInfo.getLoadBytes() == mFileInfo.getTotalBytes()) {
            _onComplete();
        } else {
            throw new DownloadException(FileUtils.formatString(
                    "Unfinished: load[%d] is not equal total[%d]!",
                    mFileInfo.getLoadBytes(), mFileInfo.getTotalBytes()));
        }
    } finally {
        if (inputStream != null) {
            inputStream.close();
        }
        if (accessFile != null) {
            accessFile.close();
        }
    }
}
 
Example 18
Project: https-github.com-apache-zookeeper   File: ZkDatabaseCorruptionTest.java   Source Code and License Vote up 4 votes
private void corruptFile(File f) throws IOException {
    RandomAccessFile outFile = new RandomAccessFile(f, "rw");
    outFile.write("fail servers".getBytes());
    outFile.close();
}
 
Example 19
Project: fuck_zookeeper   File: ZkDatabaseCorruptionTest.java   Source Code and License Vote up 4 votes
private void corruptFile(File f) throws IOException {
    RandomAccessFile outFile = new RandomAccessFile(f, "rw");
    outFile.write("fail servers".getBytes());
    outFile.close();
}
 
Example 20
Project: openjdk-jdk10   File: Basic.java   Source Code and License Vote up 4 votes
public static void main(String[] args) throws Exception {
    setup();

    show(rwFile);
    testFile(rwFile, true, bytes.length);
    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 (!dir.mkdir() || !dir.exists() || !dir.isDirectory()) {
        fail(dir, "could not create");
    }
    if (!dir.renameTo(dir2)) {
        fail(dir, "failed to rename");
    }
    if (dir.exists() || !dir2.exists() || !dir2.isDirectory()) {
        fail(dir, "not renamed");
    }

    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");
    }

}