Reputation: 159
I am trying to write a program that save into a .txt the data of a sinwave but when I execute the program it writes less (sometimes even nothing) that it should. Here is the code:
public static void main(String[] args) {
GeneradorSeñal gs = new GeneradorSeñalSinusoidal("sgsg");
Double salida;
try{
FileOutputStream out = new FileOutputStream("out.txt");
OutputStreamWriter muestras = new OutputStreamWriter(out);
for(int i=0; i<500; i++){
salida=gs.getSalida();
muestras.write(String.valueOf(salida)+"\n");
System.out.println(i+"\t"+salida);
}
}catch(Exception e){
e.getStackTrace();
}
}
GeneradorSeñal and GeneradorSeñalSinusoidal are the classes that create the sinusoidal. gs.getSalida() returns the value of the sinusoidal, the sinusoidal class works well, it is not the problem.
Upvotes: 0
Views: 76
Reputation: 72884
Make sure to always invoke the close()
method of the output stream. This makes sure all buffered data are written to the stream.
Also if you're writing characters, it's more convenient to use a FileWriter
instead.
Upvotes: 5
Reputation: 179
I improved your code a bit:
... ...
try{
FileOutputStream out = new FileOutputStream("out.txt");
OutputStreamWriter muestras = new OutputStreamWriter(out);
for(int i=0; i<500; i++){
salida=gs.getSalida();
muestras.write(String.valueOf(salida)+"\n");
System.out.println(i+"\t"+salida);
}
muestras.flush();
}catch(Exception e){
e.printStackTrace();
}finally{
if(out!=null){
try{out.close();}
catch(Throwable e){
e.printStackTrace();
}
}
}
Use finally to ensure the output stream is 100% closed.And use "out!=null" in case of out is not initialised. Close the 'out' instead of closing "muestras" in case of out is open but "muestras" is not.
Upvotes: 0
Reputation: 1421
Try this ..
try{
for(int i=0; i<500; i++){
salida=gs.getSalida();
muestras.write(String.valueOf(salida)+"\n");
muestras.flush();
System.out.println(i+"\t"+salida);
}
}catch(IOException ioe){
ioe.printStackTrace();
}finally{
try{
muestras.close();
}finally{}
}
Upvotes: 0