954,545 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

how to write to txt file

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

thijo
Newbie Poster
12 posts since Feb 2009
Reputation Points: 10
Solved Threads: 0
 

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

verruckt24
Posting Shark
952 posts since Nov 2008
Reputation Points: 485
Solved Threads: 89
 

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

javaAddict
Nearly a Senior Poster
Team Colleague
3,329 posts since Dec 2007
Reputation Points: 1,014
Solved Threads: 448
 

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

javaAddict
Nearly a Senior Poster
Team Colleague
3,329 posts since Dec 2007
Reputation Points: 1,014
Solved Threads: 448
 

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

thijo
Newbie Poster
12 posts since Feb 2009
Reputation Points: 10
Solved Threads: 0
 

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.

BestJewSinceJC
Posting Maven
2,772 posts since Sep 2008
Reputation Points: 874
Solved Threads: 354
 

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");
javaAddict
Nearly a Senior Poster
Team Colleague
3,329 posts since Dec 2007
Reputation Points: 1,014
Solved Threads: 448
 

Good call.

BestJewSinceJC
Posting Maven
2,772 posts since Sep 2008
Reputation Points: 874
Solved Threads: 354
 
Good call.

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

javaAddict
Nearly a Senior Poster
Team Colleague
3,329 posts since Dec 2007
Reputation Points: 1,014
Solved Threads: 448
 

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

javaAddict
Nearly a Senior Poster
Team Colleague
3,329 posts since Dec 2007
Reputation Points: 1,014
Solved Threads: 448
 

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.

thijo
Newbie Poster
12 posts since Feb 2009
Reputation Points: 10
Solved Threads: 0
 

See the example that I mentioned in post # 2

verruckt24
Posting Shark
952 posts since Nov 2008
Reputation Points: 485
Solved Threads: 89
 

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);
        }

    }
}
Killer_Typo
Master Poster
781 posts since Apr 2004
Reputation Points: 152
Solved Threads: 39
 

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.

lelakijadian
Newbie Poster
1 post since Mar 2009
Reputation Points: 10
Solved Threads: 0
 
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

javaAddict
Nearly a Senior Poster
Team Colleague
3,329 posts since Dec 2007
Reputation Points: 1,014
Solved Threads: 448
 

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

Lisa1110
Newbie Poster
2 posts since Jan 2009
Reputation Points: 8
Solved Threads: 0
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You