Java Code Examples for java.io.RandomAccessFile#writeBytes()

The following examples show how to use java.io.RandomAccessFile#writeBytes() . 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: ByteStore.java    From COLA with GNU Lesser General Public License v2.1 6 votes vote down vote up
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 2
Source File: RandomAccessFileTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * java.io.RandomAccessFile#readFully(byte[], int, int)
 */
public void test_readFully$BII() throws IOException {
    // Test for method void java.io.RandomAccessFile.readFully(byte [], int,
    // int)
    byte[] buf = new byte[10];
    RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
    raf.writeBytes("HelloWorld");
    raf.seek(0);
    raf.readFully(buf, 0, buf.length);
    assertEquals("Incorrect bytes read/written", "HelloWorld", new String(
            buf, 0, 10, "UTF-8"));
    try {
        raf.readFully(buf, 0, buf.length);
        fail("Reading past end of buffer did not throw EOFException");
    } catch (EOFException e) {
    }
    raf.close();
}
 
Example 3
Source File: RandomAccessFileTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * java.io.RandomAccessFile#skipBytes(int)
 */
public void test_skipBytesI() throws IOException {
    // Test for method int java.io.RandomAccessFile.skipBytes(int)
    byte[] buf = new byte[5];
    RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
    raf.writeBytes("HelloWorld");
    raf.seek(0);
    raf.skipBytes(5);
    raf.readFully(buf);
    assertEquals("Failed to skip bytes", "World", new String(buf, 0, 5, "UTF-8"));
    raf.close();
}
 
Example 4
Source File: Storage.java    From hadoop-gpu with Apache License 2.0 5 votes vote down vote up
protected void writeCorruptedData(RandomAccessFile file) throws IOException {
  final String messageForPreUpgradeVersion =
    "\nThis file is INTENTIONALLY CORRUPTED so that versions\n"
    + "of Hadoop prior to 0.13 (which are incompatible\n"
    + "with this directory layout) will fail to start.\n";

  file.seek(0);
  file.writeInt(FSConstants.LAYOUT_VERSION);
  org.apache.hadoop.io.UTF8.writeString(file, "");
  file.writeBytes(messageForPreUpgradeVersion);
  file.getFD().sync();
}
 
Example 5
Source File: Storage.java    From RDFS with Apache License 2.0 5 votes vote down vote up
protected void writeCorruptedData(RandomAccessFile file) throws IOException {
  final String messageForPreUpgradeVersion =
    "\nThis file is INTENTIONALLY CORRUPTED so that versions\n"
    + "of Hadoop prior to 0.13 (which are incompatible\n"
    + "with this directory layout) will fail to start.\n";

  file.seek(0);
  file.writeInt(FSConstants.LAYOUT_VERSION);
  org.apache.hadoop.io.UTF8.writeString(file, "");
  file.writeBytes(messageForPreUpgradeVersion);
  file.getFD().sync();
}
 
Example 6
Source File: Config.java    From seventh with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Saves the configuration file
 * 
 * @param filename
 * @throws IOException
 */
public void save(String filename) throws IOException {
    File file = new File(filename);
    RandomAccessFile output = new RandomAccessFile(file, "rw");
    try {
        output.setLength(0);
        output.writeBytes(this.configName + " = ");
        writeOutObject(output, config, 0);
    }
    finally {
        output.close();
    }
}
 
Example 7
Source File: OldRandomAccessFileTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * java.io.RandomAccessFile#skipBytes(int)
 */
public void test_skipBytesI() throws IOException {
    byte[] buf = new byte[5];
    RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
    raf.writeBytes("HelloWorld");
    raf.seek(0);

    assertTrue("Test 1: Nothing should be skipped if parameter is less than zero",
            raf.skipBytes(-1) == 0);

    assertEquals("Test 4: Incorrect number of bytes skipped; ",
            5, raf.skipBytes(5));

    raf.readFully(buf);
    assertEquals("Test 3: Failed to skip bytes.",
            "World", new String(buf, 0, 5));

    raf.seek(0);
    assertEquals("Test 4: Incorrect number of bytes skipped; ",
            10, raf.skipBytes(20));

    raf.close();
    try {
        raf.skipBytes(1);
        fail("Test 5: IOException expected.");
    } catch (IOException e) {
        // Expected.
    }
}
 
Example 8
Source File: RandomAccessFileTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * java.io.RandomAccessFile#writeBytes(java.lang.String)
 */
public void test_writeBytesLjava_lang_String() throws IOException {
    // Test for method void
    // java.io.RandomAccessFile.writeBytes(java.lang.String)
    byte[] buf = new byte[10];
    RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
    raf.writeBytes("HelloWorld");
    raf.seek(0);
    raf.readFully(buf);
    assertEquals("Incorrect bytes read/written", "HelloWorld", new String(
            buf, 0, 10, "UTF-8"));
    raf.close();

}
 
Example 9
Source File: RandomAccessFileTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * java.io.RandomAccessFile#readFully(byte[])
 */
public void test_readFully$B() throws IOException {
    // Test for method void java.io.RandomAccessFile.readFully(byte [])
    byte[] buf = new byte[10];
    RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
    raf.writeBytes("HelloWorld");
    raf.seek(0);
    raf.readFully(buf);
    assertEquals("Incorrect bytes read/written", "HelloWorld", new String(
            buf, 0, 10, "UTF-8"));
    raf.close();
}
 
Example 10
Source File: Zystem.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void filewrite( String s )
{
	try {
		RandomAccessFile w =
			new RandomAccessFile( target, "rw" );
		w.seek( w.length() );
		w.writeBytes( s );
		w.close();
	} catch ( Exception e ) {
		System.out.println("Debug output file write failed");
	}
}
 
Example 11
Source File: IOUtil.java    From SEANLP with Apache License 2.0 5 votes vote down vote up
/**
 * 追加文件:使用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();
	}
}
 
Example 12
Source File: DataGen.java    From rubix with Apache License 2.0 5 votes vote down vote up
public static void writeZerosInFile(String filename, int start, int end) throws IOException
{
  File file = new File(filename);
  RandomAccessFile raf = new RandomAccessFile(file, "rw");
  raf.seek(start);
  String s = "0";
  StandardCharsets.UTF_8.encode(s);
  for (int i = 0; i < (end - start); i++) {
    raf.writeBytes(s);
  }
  raf.close();
}
 
Example 13
Source File: RandomAccessFileWriteDemo.java    From javacore with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
public static void main(String[] args) throws IOException {

        // 指定要操作的文件
        File f = new File("temp.log");

        // 声明RandomAccessFile类的对象,读写模式,如果文件不存在,会自动创建
        RandomAccessFile rdf = new RandomAccessFile(f, "rw");

        // 写入一组记录
        String name = "zhangsan";
        int age = 30;
        rdf.writeBytes(name);
        rdf.writeInt(age);

        // 写入一组记录
        name = "lisi    ";
        age = 31;
        rdf.writeBytes(name);
        rdf.writeInt(age);

        // 写入一组记录
        name = "wangwu  ";
        age = 32;
        rdf.writeBytes(name);
        rdf.writeInt(age);

        // 关闭
        rdf.close();
    }
 
Example 14
Source File: PlatformWithAbsolutePathTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testPlatformWithAbsolutePath() throws Exception {
    File wd = new File(getWorkDir(), "currentdir");
    wd.mkdirs();
    URL u = Lookup.class.getProtectionDomain().getCodeSource().getLocation();
    File utilFile = new File(u.toURI());
    assertTrue("file found: " + utilFile, utilFile.exists());
    File root = utilFile.getParentFile().getParentFile().getParentFile();
    File bin = new File(root,"bin");
    File newBin = new File(wd,"bin");
    newBin.mkdirs();
    File newEtc = new File(wd,"etc");
    newEtc.mkdirs();
    File[] binFiles = bin.listFiles();
    for (File f : binFiles) {
        File newFile = new File(newBin,f.getName());
        FileChannel newChannel = new RandomAccessFile(newFile,"rw").getChannel();
        new RandomAccessFile(f,"r").getChannel().transferTo(0,f.length(),newChannel);
        newChannel.close();
    }
    RandomAccessFile netbeansCluster = new RandomAccessFile(new File(newEtc,"netbeans.clusters"),"rw");
    netbeansCluster.writeBytes(utilFile.getParentFile().getParent()+"\n");
    netbeansCluster.close();
    String str = "1 * * * *";
    run(wd, str);
    
    String[] args = MainCallback.getArgs(getWorkDir());
    assertNotNull("args passed in", args);
    List<String> a = Arrays.asList(args);
    if (!a.contains(str)) {
        fail(str + " should be there: " + a);
    }
}
 
Example 15
Source File: ScrubTest.java    From stratio-cassandra with Apache License 2.0 4 votes vote down vote up
@Test
public void testScrubCorruptedCounterRow() throws IOException, WriteTimeoutException
{
    // skip the test when compression is enabled until CASSANDRA-9140 is complete
    assumeTrue(!Boolean.parseBoolean(System.getProperty("cassandra.test.compression", "false")));

    CompactionManager.instance.disableAutoCompaction();
    Keyspace keyspace = Keyspace.open(KEYSPACE);
    ColumnFamilyStore cfs = keyspace.getColumnFamilyStore(COUNTER_CF);
    cfs.clearUnsafe();

    fillCounterCF(cfs, 2);

    List<Row> rows = cfs.getRangeSlice(Util.range("", ""), null, new IdentityQueryFilter(), 1000);
    assertEquals(2, rows.size());

    SSTableReader sstable = cfs.getSSTables().iterator().next();

    // overwrite one row with garbage
    long row0Start = sstable.getPosition(RowPosition.ForKey.get(ByteBufferUtil.bytes("0"), sstable.partitioner), SSTableReader.Operator.EQ).position;
    long row1Start = sstable.getPosition(RowPosition.ForKey.get(ByteBufferUtil.bytes("1"), sstable.partitioner), SSTableReader.Operator.EQ).position;
    long startPosition = row0Start < row1Start ? row0Start : row1Start;
    long endPosition = row0Start < row1Start ? row1Start : row0Start;

    RandomAccessFile file = new RandomAccessFile(sstable.getFilename(), "rw");
    file.seek(startPosition);
    file.writeBytes(StringUtils.repeat('z', (int) (endPosition - startPosition)));
    file.close();

    // with skipCorrupted == false, the scrub is expected to fail
    Scrubber scrubber = new Scrubber(cfs, sstable, false, false);
    try
    {
        scrubber.scrub();
        fail("Expected a CorruptSSTableException to be thrown");
    }
    catch (IOError err) {}

    // with skipCorrupted == true, the corrupt row will be skipped
    scrubber = new Scrubber(cfs, sstable, true, false);
    scrubber.scrub();
    scrubber.close();
    assertEquals(1, cfs.getSSTables().size());

    // verify that we can read all of the rows, and there is now one less row
    rows = cfs.getRangeSlice(Util.range("", ""), null, new IdentityQueryFilter(), 1000);
    assertEquals(1, rows.size());
}
 
Example 16
Source File: PegasusSubmitDAG.java    From pegasus with Apache License 2.0 4 votes vote down vote up
/**
 * Modifies the dagman condor submit file for metrics reporting.
 *
 * @param file
 * @return true if file is modified, else false
 * @throws CodeGeneratorException
 */
protected boolean modifyDAGManSubmitFileForMetrics(File file) throws CodeGeneratorException {
    // modify the environment string to add the environment for
    // enabling DAGMan metrics if so required.
    Metrics metricsReporter = new Metrics();
    metricsReporter.initialize(mBag);
    ENV env = metricsReporter.getDAGManMetricsEnv();
    if (env.isEmpty()) {
        return false;
    } else {
        // we read the DAGMan submit file in and grab the environment from it
        // and add the environment key to the second last line with the
        // Pegasus metrics environment variables added.
        try {
            RandomAccessFile raf = new RandomAccessFile(file, "rw");
            String dagmanEnvString = "";
            String line = null;
            long previous = raf.getFilePointer();
            while ((line = raf.readLine()) != null) {
                if (line.startsWith("environment")) {
                    dagmanEnvString = line;
                }
                if (line.startsWith("queue")) {
                    // backtrack to previous file position i.e just before queue
                    raf.seek(previous);
                    StringBuilder dagmanEnv = new StringBuilder(dagmanEnvString);
                    if (dagmanEnvString.isEmpty()) {
                        dagmanEnv.append("environment=");
                    } else {
                        dagmanEnv.append(";");
                    }
                    for (Iterator it = env.getProfileKeyIterator(); it.hasNext(); ) {
                        String key = (String) it.next();
                        dagmanEnv.append(key).append("=").append(env.get(key)).append(";");
                    }
                    mLogger.log(
                            "Updated environment for dagman is " + dagmanEnv.toString(),
                            LogManager.DEBUG_MESSAGE_LEVEL);
                    raf.writeBytes(dagmanEnv.toString());
                    raf.writeBytes(System.getProperty("line.separator", "\r\n"));
                    raf.writeBytes("queue");
                    break;
                }
                previous = raf.getFilePointer();
            }

            raf.close();
        } catch (IOException e) {
            throw new CodeGeneratorException(
                    "Error while reading dagman .condor.sub file " + file, e);
        }
    }
    return true;
}
 
Example 17
Source File: ReloadLibraryTest.java    From birt with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Tests needSave method.
 * 
 * Only change happens directly on report design, isDirty mark of report
 * design is true. So when library changed, isDirty mark of report design
 * should be false.
 * 
 * <ul>
 * <li>reload error library and throw out exception</li>
 * <li>isDirty not changed</li>
 * 
 * </ul>
 * 
 * @throws Exception
 */

public void testErrorLibraryNeedsSave( ) throws Exception
{
	List fileNames = new ArrayList( );
	fileNames.add( INPUT_FOLDER + "DesignWithSaveStateTest.xml" ); //$NON-NLS-1$
	fileNames.add( INPUT_FOLDER + "LibraryWithSaveStateTest.xml" ); //$NON-NLS-1$

	List filePaths = dumpDesignAndLibrariesToFile( fileNames );
	String designFilePath = (String) filePaths.get( 0 );
	openDesign( designFilePath, false );

	String libFilePath = (String) filePaths.get( 1 );
	openLibrary( libFilePath, false );

	LabelHandle labelHandle = designHandle.getElementFactory( ).newLabel(
			"new test label" );//$NON-NLS-1$
	designHandle.getBody( ).add( labelHandle );

	assertTrue( designHandle.needsSave( ) );
	assertTrue( designHandle.getCommandStack( ).canUndo( ) );
	assertFalse( designHandle.getCommandStack( ).canRedo( ) );

	ActivityStack stack = (ActivityStack) designHandle.getCommandStack( );

	File f = new File( libFilePath );
	RandomAccessFile raf = new RandomAccessFile( f, "rw" );//$NON-NLS-1$

	// Seek to end of file
	raf.seek( 906 );

	// Append to the end
	raf.writeBytes( "<label name=\"NewLabel1\"/>" );//$NON-NLS-1$
	raf.close( );

	// reloadlibrary

	try
	{
		designHandle.reloadLibrary( libraryHandle );
		fail( );
	}
	catch ( DesignFileException e )
	{

	}

	assertTrue( stack.canUndo( ) );
	assertFalse( stack.canRedo( ) );
	assertEquals( 1, stack.getCurrentTransNo( ) );
	assertTrue( designHandle.needsSave( ) );

	// restore file

	libraryHandle.close( );
	libraryHandle = null;
}
 
Example 18
Source File: TECore.java    From teamengine with Apache License 2.0 4 votes vote down vote up
public Element parse(Document parse_instruction, String xsl_version)
        throws Throwable {
  DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
  dbf.setNamespaceAware(true);
  // Fortify Mod: prevent external entity injection
  dbf.setExpandEntityReferences(false);
  DocumentBuilder db = dbf.newDocumentBuilder();

  TransformerFactory tf = TransformerFactory.newInstance();
   // Fortify Mod: prevent external entity injection 
  tf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
  Transformer t = null;
  Node content = null;
  Document parser_instruction = null;

  Element parse_element = (Element) parse_instruction
              .getElementsByTagNameNS(CTL_NS, "parse").item(0);

  NodeList children = parse_element.getChildNodes();
  for (int i = 0; i < children.getLength(); i++) {
    if (children.item(i).getNodeType() == Node.ELEMENT_NODE) {
      Element e = (Element) children.item(i);
              if (e.getNamespaceURI().equals(XSL_NS)
              && e.getLocalName().equals("output")) {
        Document doc = db.newDocument();
        Element transform = doc
                          .createElementNS(XSL_NS, "transform");
        transform.setAttribute("version", xsl_version);
        doc.appendChild(transform);
                  Element output = doc.createElementNS(XSL_NS, "output");
        NamedNodeMap atts = e.getAttributes();
        for (int j = 0; j < atts.getLength(); j++) {
          Attr a = (Attr) atts.item(i);
          output.setAttribute(a.getName(), a.getValue());
        }
        transform.appendChild(output);
                  Element template = doc.createElementNS(XSL_NS, "template");
        template.setAttribute("match", "node()|@*");
        transform.appendChild(template);
                  Element copy = doc.createElementNS(XSL_NS, "copy");
        template.appendChild(copy);
                  Element apply = doc.createElementNS(XSL_NS,
                "apply-templates");
        apply.setAttribute("select", "node()|@*");
        copy.appendChild(apply);
        t = tf.newTransformer(new DOMSource(doc));
      } else if (e.getLocalName().equals("content")) {
        NodeList children2 = e.getChildNodes();
        for (int j = 0; j < children2.getLength(); j++) {
          if (children2.item(j).getNodeType() == Node.ELEMENT_NODE) {
            content = children2.item(j);
          }
        }
        if (content == null) {
          content = children2.item(0);
        }
      } else {
        parser_instruction = db.newDocument();
        tf.newTransformer().transform(new DOMSource(e),
                new DOMResult(parser_instruction));
      }
    }
  }
  if (t == null) {
    t = tf.newTransformer();
  }
  File temp = File.createTempFile("$te_", ".xml");
  // Fortify Mod: It is possible to get here without assigning a value to content.  
  // if (content.getNodeType() == Node.TEXT_NODE) {
  if (content != null && content.getNodeType() == Node.TEXT_NODE) {
    RandomAccessFile raf = new RandomAccessFile(temp, "rw");
    raf.writeBytes(((Text) content).getTextContent());
    raf.close();
  } else {
    t.transform(new DOMSource(content), new StreamResult(temp));
  }
  URLConnection uc = temp.toURI().toURL().openConnection();
  Element result = parse(uc, parser_instruction);
  temp.delete();
  return result;
}
 
Example 19
Source File: ServiceListStore.java    From COLA with GNU Lesser General Public License v2.1 4 votes vote down vote up
private void writeLine(RandomAccessFile raf, String line) throws IOException {
    raf.writeBytes(line);
    raf.writeBytes("\r\n");
}
 
Example 20
Source File: FileIOTest.java    From ignite with Apache License 2.0 3 votes vote down vote up
/**
 * @throws Exception If failed.
 */
@Test
public void testReadLineFromBinaryFile() throws Exception {
    File file = new File(FILE_PATH);

    file.deleteOnExit();

    RandomAccessFile raf = new RandomAccessFile(file, "rw");

    byte[] b = new byte[100];

    Arrays.fill(b, (byte)10);

    raf.write(b);

    raf.writeBytes("swap-spaces/space1/b53b3a3d6ab90ce0268229151c9bde11|" +
        "b53b3a3d6ab90ce0268229151c9bde11|1315392441288" + U.nl());

    raf.writeBytes("swap-spaces/space1/b53b3a3d6ab90ce0268229151c9bde11|" +
        "b53b3a3d6ab90ce0268229151c9bde11|1315392441288" + U.nl());

    raf.write(b);

    raf.writeBytes("test" + U.nl());

    raf.getFD().sync();

    raf.seek(0);

    while (raf.getFilePointer() < raf.length()) {
        String s = raf.readLine();

        X.println("String: " + s + ";");

        X.println("String length: " + s.length());

        X.println("File pointer: " + raf.getFilePointer());
    }
}