当我使用下面显示的代码时,我真的很困惑为什么我得到一个0kb的文件。作为关于这个类的Java网站的指导,我应该工作。但是......我想生成一个正弦波并将其结果输出到txt填充为double。这是我的代码的第一步,我陷入了这么简单的问题。也许我不太了解如何使用类文件和数据流,就像我从官方网站上学到的那样。
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();
}
}
}
答案 0 :(得分:1)
问题是,当您完成后,您并未关闭流。他们正在缓冲数据,并且在销毁数据时不会自动刷新内容,因此所有数据都会丢失。
答案 1 :(得分:0)
writeDouble()
。这就是它的作用。如果您需要字符串,请使用BufferedWriter
或PrintWriter
。所有这些:
if(file.exists()){
file.delete();
}
try {
file.createNewFile();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
不仅是不必要的:它是浪费的。 new FileOutputStream
已经做到了这一切。您将创建文件的开销增加了一倍或三倍;你是非原子地做的;而你又浪费时间和空间。全部删除。