Input/Output Writing to a Text File

PHOTO EMBED

Sun Jan 16 2022 06:21:23 GMT+0000 (UTC)

Saved by @mikemcnik #java

//Construct a java.io.File object and pass the file anme as an argument
import java.io.File;
import java.io.PrintWriter;

String fname = "output.txt";

File file = new File(fname);

//Then pass the file object as an argument to the java.io.PrintWriter class
PrintWriter out = new PrintWriter(file);

//They can be combined together
PrintWriter out = new PrintWriter(new File(fname));

//EXAMPLE

int x = 20;
double y = 3.14159265;
char ch1 = '$', ch2 = 'A';
String s1 = "Fred", s2 = "Flintstone";
PrintWriter out = PrintWriter(new File("output.txt")); //opens a file for writing
out.print(x + " " + y); 
out.println(ch1);
out.println(ch2 + " " + s2 + ", " + s1);
out.close;

/* 
OUTPUT:
20 3.14159265
$
A Flintstone, Fred
*/
content_copyCOPY

Writing to a TXT File.