2016-06-08 54 views
0

我真的很困惑,爲什麼當我使用下面顯示的代碼時,我得到一個0kb文件。作爲Java網站關於這個類的說明,我應該工作。但是...我想要生成一個正弦波並輸出其結果到一個txt填充雙。這是我的代碼的第一步,我陷入了這樣一個簡單的問題。也許我不太瞭解如何使用類文件和數據流,就像我從官方網站上學到的那樣。爲什麼我在使用datainputstream,java,android時會得到一個0kb文件?

public class audioplayThread implements Runnable { 
private File file; 
private FileOutputStream ops; 
private BufferedOutputStream bos; 
private DataOutputStream dos; 
private double Omega; 
private int f = 18*1000; 
private double pi; 
private int samplenumber = 84;  //Assume OFDM symbol has 64 real value and 
private static final int Encording = AudioFormat.ENCODING_PCM_16BIT; //Data size for each frame = 16 bytes 
private static final int Sample_rate = 48000;      //Sample rate = 48000 HZ 
private static final int Channel = AudioFormat.CHANNEL_OUT_MONO;   //Set as single track 
private static final int Buffersize = AudioTrack.getMinBufferSize(Sample_rate, Channel,Encording); 
@Override 
public void run() { 
    // TODO Auto-generated method stub 
    file = new File(Environment.getExternalStorageDirectory().getAbsoluteFile(),"mmm.txt"); 
    if(file.exists()){ 
     file.delete(); 
    } 
    try { 
     file.createNewFile(); 
    } catch (IOException e1) { 
     // TODO Auto-generated catch block 
     e1.printStackTrace(); 
    } 
    try { 
     /*Create a datastream*/ 
     ops = new FileOutputStream(file); 
     bos = new BufferedOutputStream(ops); 
     dos = new DataOutputStream(bos); 
     /*Set sine wave parameter*/ 
     pi = Math.PI; 
     Omega = 2*pi*f/Sample_rate; 

     /*Build instance for audiotrack*/ 
     //AudioTrack at = new AudioTrack(AudioManager.STREAM_MUSIC,Sample_rate, Channel, Encording, Buffersize, AudioTrack.MODE_STREAM); 

     /*build sine wave*/ 
     double[] buffer = new double[samplenumber]; 
     for(int i=0;i<samplenumber;i++){ 
      buffer[i] = Math.sin(Omega*i); 
      dos.writeDouble(buffer[i]); 

     } 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
} 

}

+1

您是否試過關閉流?你正在緩衝,從不關閉它們,數據可能會丟失v –

+0

呃......我很愚蠢,我怎麼能忘記關閉它。謝謝!還有一個問題,爲什麼我在txt文件中獲取這些數據是不可讀的代碼? – MarvinC

+0

因爲您使用的是使用二進制格式的'DataOutputStream'。 –

回答

1

的問題是,你不關閉流時,你就大功告成了。他們正在緩衝數據,並且不會在內容被銷燬時自動刷新內容,因此所有數據都將丟失。

+0

謝謝!我明白了! – MarvinC

0
  1. 由於您從不關閉輸出流,因此您將獲得空輸出。它是緩衝的,它會保持緩衝,直到你刷新或關閉它。
  2. 由於您打電話給writeDouble(),因此您會收到二進制文件。這就是它的作用。如果您想要字符串,請使用BufferedWriterPrintWriter
  3. 這一切:

    if(file.exists()){ 
        file.delete(); 
    } 
    try { 
        file.createNewFile(); 
    } catch (IOException e1) { 
        // TODO Auto-generated catch block 
        e1.printStackTrace(); 
    } 
    

    不僅是不必要的:它是一種浪費。 new FileOutputStream已經做到了。您將創建文件的開銷增加一倍或三倍;你是以非原子的方式做它;而你正在浪費時間和空間。全部刪除。

相關問題