hi,
I have to write my output of a java program to a txt file.
how to do this in java
thanks

Recommended Answers

All 17 Replies

Take a look at the Java I/O package. I am sure it's a monster containing hundreads of classes but it present as many ways as there can be to write to a file in Java.

OR

You can use a PrintWriter over an OutputStream like the FileOutputStream. The FileOutputStream can be opened on a File object, or a string that specifies the filepath.

OR

For a quick example check here

You can use BufferedWriter to write to a file:

FileWriter fWriter = null;
BufferedWriter writer = null; 
try {
  fWriter = new FileWriter("fileName");
  writer = new BufferedWriter(fWriter);

  //WRITES 1 LINE TO FILE AND CHANGES LINE
  writer.write("This line is written");
  writer.newLine();


   writer.close();
} catch (Exception e) {

}

Also check these APIs
BufferedWriter
The BufferedWriter's super class: Writer
FileWriter

Take a look at the Java I/O package. I am sure it's a monster containing hundreads of classes but it present as many ways as there can be to write to a file in Java.

OR

You can use a PrintWriter over an OutputStream like the FileOutputStream. The FileOutputStream can be opened on a File object, or a string that specifies the filepath.

OR

For a quick example check here

Together almost the same post

sir,
i'm trying to add 2 nos.i have the code

import java.io.*;
/* 
 * Adds 2 integers given by the user, then prints out the sum. 
 */ 


public class Add2number { 

            public static void main(String[] args) throws IOException { 
            BufferedReader stdin = new BufferedReader( 
                  new InputStreamReader(System.in)); 
          
            //asks user for 1st number, then converts it to an integer 
            System.out.print("Enter first integer: "); 
            int x = Integer.parseInt(stdin.readLine()); 
            //asks user for 2nd number, than converts it to an integer 
            System.out.print("Enter second integer: "); 
            int y = Integer.parseInt(stdin.readLine()); 

            //add x,y 
            int sum = x + y; 

            //Display sum of x,y 
            System.out.println("The sum is: " + sum); 
      }//ends main 

}//ends addReadLine

[output]
Enter first integer:12
Enter second integer:13
The sum is :25
[/output]

fine
if i want to print this output to a text file
i use another class Using.java

public class Using{
public static void main(String args[]) {

    
       try {
Process p = Runtime.getRuntime().exec("java Add2number>C:\\Program Files\\Java\\jdk1.6.0_03\\bin \\out.txt");
} catch(Exception e) {
System.err.println(e);
			System.exit(-1);
} 
 } }

the output is not redirected in out.txt .i don't know where i'm going wrong.can you help in this code to print my output in a text file

If you want to use that code, I'd suggest you simply copy and paste it into another file, and edit it so that it sends its output to a text file rather than prints it on the screen. You can use PrintWriter to do this.

I haven't written this kind of java code before but I am familiar with the redirect command: '>'

Maybe this is your problem:

Process p = Runtime.getRuntime().exec("java Add2number>C:\\Program Files\\Java\\jdk1.6.0_03\\bin \\out.txt");

Have you noticed a space between \\bin and \\out
...\\bin \\out
Can you try it with this:

Process p = Runtime.getRuntime().exec("java Add2number>C:\\Program Files\\Java\\jdk1.6.0_03\\bin\\out.txt");

Good call.

I don't know if this solves the problem. We will need thijo to reply with an update of his problem

I see that you marked the thread solved.
What was the problem?

hi,
I think the problem could not be solved since we cannot implement user interaction using java runtime(). so i just used buffered file writer if you have any suggestion plz inform me.

See the example that I mentioned in post # 2

you need to preappend

cmd /c

my example I tested:

package redirectconsoleoutput;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 *
 * @author Michael
 */
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main( String[] args ) {
        // TODO code application logic here
        System.out.println("Attempting to redirect the output of one java app to another");
        String s = null;

        try {
            Process p = Runtime.getRuntime().exec("cmd /c java -jar \"D:\\Users\\Michael\\Documents\\NetBeansProjects\\SortedSetReWrite\\dist\\SortedSetReWrite.jar\" > \"D:\\SortedSetReWrite.txt\"");

            BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));

            BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));

            // read the output from the command

            System.out.println("Here is the standard output of the command:\n");
            while ( (s = stdInput.readLine()) != null ) {
                System.out.println(s);
            }

            // read any errors from the attempted command

            System.out.println("Here is the standard error of the command (if any):\n");
            while ( (s = stdError.readLine()) != null ) {
                System.out.println(s);
            }

            System.exit(0);

        } catch ( IOException e ) {
            System.out.println(e.getMessage());
            System.exit(-1);
        }

    }
}

hey guys...i have one question.i have file Sample.data, in that file i write "Hello world". how to write code to separate word between "Hello" and "world" and print out it as output seperately.

hey guys...i have one question.i have file Sample.data, in that file i write "Hello world". how to write code to separate word between "Hello" and "world" and print out it as output seperately.

Start a new thread.

Or better search this forum. Your question has been answered a million times

You can use a PrintWriter over an OutputStream like the FileOutputStream. The FileOutputStream can be opened on a File object, or a string that specifies the filepath.

Lisa11

<snip fake signature>

hi
i want to write my java output to a text file and from text file to database.i am able to write to a text file, form text file i am not able to write to a database how to write the code for it tell me plzzz....

Hello kssk

Please note the DaniWeb rules, including
"Do not hijack old forum threads by posting a new question as a reply to an old one"

Please start a new topic for your question, and also remember
"Do provide evidence of having done some work yourself if posting questions from school or work assignments"

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.