user1277399
user1277399

Reputation: 81

Print output in textfile in java

public static void main(String[] args) {

int i;
float[] npoints = new float[10];
float[] points = new float[10];
points[0]=(float) 0.3;
points[1]=(float) 0.2;
points[2]=(float) 0.4;
points[3]=(float) 0.5;
points[4]=(float) 0.6;
points[5]=(float) 0.0123;

for(i=0;i<6;i++)
{
    if(points[i]!=0.0)
    {
        npoints[i]=points[i];
        System.out.println(i+":"+points[i]);
    }

}
System.out.println(npoints[i]);
}

output:

run:
    0:0.3
    1:0.88
    2:0.22
    3:0.95
    4:0.16
    5:0.0123
[0.95, 0.88, 0.3, 0.22, 0.16, 0.0123]
BUILD SUCCESSFUL (total time: 0 seconds)
`

I want to print this output in a textfile, any suggestions? I am new to java

Upvotes: 0

Views: 271

Answers (3)

arshajii
arshajii

Reputation: 129497

Create a new BufferedWriter:

BufferedWriter bw = new BufferedWriter(new FileWriter("somefilename.txt"));

Then use the write method:

bw.write(i+":"+points[i]);  // or bw.write(anything else)

Don't forger to close this BufferedWriter when you're finished:

bw.close();

Also, remember to import the appropriate classes from java.io, and to handle the IOException.

Relevant Javadocs:

Upvotes: 1

pl4g4
pl4g4

Reputation: 101

try this code -- change This is line 1 for what u need to print

import java.io.*;

public class WriteText{
   public static void main(String[] args){
       try {
           FileWriter outFile = new FileWriter(args[0]);
          PrintWriter out = new PrintWriter(outFile);

          // Also could be written as follows on one line
          // Printwriter out = new PrintWriter(new FileWriter(args[0]));

          // Write text to file
          out.println("This is line 1");
          out.println("This is line 2");
          out.print("This is line3 part 1, ");
          out.println("this is line 3 part 2");
          out.close();
      } catch (IOException e){
          e.printStackTrace();
      }
  }

}

Upvotes: 0

kosa
kosa

Reputation: 66637

You may use something like buffered writer

   FileWriter fw = new FileWriter(fileObj);
   BufferedWriter bw = new BufferedWriter(fw);
   bw.write(content);
   bw.close();

Upvotes: 1

Related Questions