java.io.RandomAccessFile#writeBytes ( )源码实例Demo

下面列出了java.io.RandomAccessFile#writeBytes ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: COLA   文件: ByteStore.java
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();
    }
 
源代码2 项目: j2objc   文件: RandomAccessFileTest.java
/**
 * 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();
}
 
源代码3 项目: netbeans   文件: PlatformWithAbsolutePathTest.java
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);
    }
}
 
源代码4 项目: javacore   文件: RandomAccessFileWriteDemo.java
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();
    }
 
源代码5 项目: rubix   文件: DataGen.java
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();
}
 
源代码6 项目: SEANLP   文件: IOUtil.java
/**
 * 追加文件:使用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();
	}
}
 
源代码7 项目: knopflerfish.org   文件: Zystem.java
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");
	}
}
 
源代码8 项目: j2objc   文件: RandomAccessFileTest.java
/**
 * 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();
}
 
源代码9 项目: j2objc   文件: RandomAccessFileTest.java
/**
 * 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();
}
 
源代码10 项目: j2objc   文件: RandomAccessFileTest.java
/**
 * 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();

}
 
源代码11 项目: j2objc   文件: OldRandomAccessFileTest.java
/**
 * 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.
    }
}
 
源代码12 项目: seventh   文件: Config.java
/**
 * 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();
    }
}
 
源代码13 项目: RDFS   文件: Storage.java
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();
}
 
源代码14 项目: hadoop-gpu   文件: Storage.java
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();
}
 
源代码15 项目: COLA   文件: ServiceListStore.java
private void writeLine(RandomAccessFile raf, String line) throws IOException {
    raf.writeBytes(line);
    raf.writeBytes("\r\n");
}
 
源代码16 项目: stratio-cassandra   文件: ScrubTest.java
@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());
}
 
源代码17 项目: pegasus   文件: PegasusSubmitDAG.java
/**
 * 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;
}
 
源代码18 项目: birt   文件: ReloadLibraryTest.java
/**
 * 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;
}
 
源代码19 项目: teamengine   文件: TECore.java
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;
}
 
源代码20 项目: ignite   文件: FileIOTest.java
/**
 * @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());
    }
}