Question: java programming 3.) Write a String to a File using PrintStream This time build a class WriteString. This class, when instantiated, will write a string

java programming

3.) Write a String to a File using PrintStream This time build a class WriteString. This class, when instantiated, will write a string to a file by using a PrintStream object connected to a FileOutputStream Object.

[i.e. // This code goes in main()

WriteString ws = new WriteString(f1.txt,Hello world);]

Use the File class first to interrogate the filename that was given to you. Make sure the file is empty(length = 0) before writing to the file. Use an if statement and test with try/catch to catch any exceptions

Next, Java gives us 2 Streams that we will combine to accomplish writing a String to a File. The FileOutputStream and the PrintStream classes. We will attach these 2 streams and send a String to the PrintStream, the PrintStream will send the bytes to the FileOutputStream and the FileOutputStream will send the bytes to the physical file. Code below:

String s1 = Go Braves;

File f1 = new File(filename);

long sz = f1.length();

if (size == 0) {

FileOutPutStream fout = new FileOutputStream(f1);

PrintStream ps = new PrintStream(fout);

ps.println(s1);

ps.close();

}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!