2009-04-09 48 views

回答

4

更新二進制輸出:

// There are dependencies on how you create your floatbuffer for this to work 
// I suggest starting with a byte buffer and using asFloatBuffer() when 
// you need it as floats. 
// ByteBuffer b = ByteBuffer.allocate(somesize); 
// FloatBuffer fb = b.asFloatBuffer(); 
// There will also be endiance issues when you write binary since 
// java is big-endian. You can adjust this with Buffer.order(...) 
// b.order(ByteOrder.LITTLE_ENDIAN) 
// If you're using a hex-editor you'll probably want little endian output 
// since most consumer machines (unless you've got a sparc/old mac) are little 


FileOutputStream fos = new FileOutputStream("some_binary_output_file_name"); 
FileChannel channel = fos.getChannel(); 

channel.write(byteBufferBackingYourFloatBuffer); 

fos.close(); 

文本輸出: 既然你想這是我觀看假設你想要的文本文件。你會想要使用PrintStream。

// Try-catch omitted for simplicity 

PrintStream ps = new PrintStream("some_output_file.txt"); 
for(int i = 0; i < yourFloatBuffer.capacity(); i++) 
{ 
    // put each float on one line 
    // use printf to get fancy (decimal places, etc) 
    ps.println(yourFloagBuffer.get(i)); 
} 

ps.close(); 

沒有時間發佈完整的原始/二進制(非文本)版本。如果你想這樣做,使用FileOutputStream,得到FileChannel,並直接寫FloatBuffer(因爲它是一個ByteBuffer)通過你的緩衝區的支持數組

+0

謝謝,儘管我其實想這一切寫出來的二進制文件。對不起,沒有具體說明,我會更新問題。 – jblocksom 2009-04-09 19:50:45

-1

這種迭代並輸出每個浮動。用你自己的參數替換文本文件和floatBuffer。

PrintStream out = new PrintStream("target.txt"); 
for(float f : floatBuffer.array()){ 
    out.println(f); 
} 
out.close(); 
2

Asusming你想要的數據爲二進制:

開始用ByteBuffer。撥打asFloatBuffer即可獲得您的FloatBuffer。當你完成你的東西時,將ByteBuffer保存到WritableByteChannel

如果你已經有FloatBuffer它可以從複製到步驟2的緩衝區。

低性能但更簡單的方法是使用Float.floatToIntBit

(留意字節序,很明顯。)

相關問題