Question

In: Computer Science

What method is used to set up a file for reading and/or writing?

What method is used to set up a file for reading and/or writing?

Solutions

Expert Solution

Note :

I write this for java language.

stream can be defined as a sequence of data. The InputStream is used to read data from a source and the OutputStream is used for writing data to a destination.

==> FileInputStream

This stream is used for reading data from the files. Objects can be created using the keyword new and there are several types of constructors available.

InputStream f = new FileInputStream("C:/java/hello");

==> FileOutputStream
FileOutputStream is used to create a file and write data into it. The stream would create a file, if it doesn't already exist, before opening it for output.

OutputStream f = new FileOutputStream("C:/java/hello")

Create a File
To create a file in Java, you can use the createNewFile() method. This method returns a boolean value: true if file is successfully create, and false if the file already exists.


Note that the method is enclosed in a try...catch block. This is necessary because it throws an IOException if an error occurs:

code to create file:

import java.io.File; // Import the File class
import java.io.IOException; // Import the IOException class to handle errors

public class CreateFile
{
public static void main(String[] args)
{
try
{
File myObj = new File("filename.txt");
if (myObj.createNewFile())
{
System.out.println("File created successfully : " + myObj.getName());
} else
{
System.out.println("File already exists in system .");
}
}
catch (IOException e)
{
System.out.println("An error occurred .");
e.printStackTrace();
}
}
}

Write To a File
FileWriter class together with its write() method to write some text to the file we created in the example above.
Note that when you are done writing to the file, you should close it with the close() method:

code:

import java.io.FileWriter;
import java.io.IOException;

public class WriteToFile
{
public static void main(String[] args)
{
try
{
FileWriter myWriter = new FileWriter("filename.txt");
myWriter.write("My name is Bob , i am engineer");
myWriter.close();
System.out.println("Successfully wrote to the file.");
}
catch (IOException e)
{
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}

Read a File
The Scanner class to read the contents of the text file.

In modern Java applications you typically use the java.nio.file API to read and write files.

Java will read all input as a stream of bytes. The InputStream class is the superclass of all classes representing an input stream of bytes

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

// somewhere in your code

String content = new String(Files.readAllBytes(Paths.get(fileName)));
To read a text file line by line into a List of type String structure you can use the Files.readAllLines method.

List<String> lines = Files.readAllLines(Paths.get(fileName));

code:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ReadFile
{
public static void main(String[] args)
{
try
{
File myObj = new File("filename.txt");
Scanner myReader = new Scanner(myObj);
while (myReader.hasNextLine())
{
String data = myReader.nextLine();
System.out.println(data);
}
myReader.close();
}
catch (FileNotFoundException e)
{
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}


Related Solutions

What method is used to set up a file for reading and/or writing? code in python
What method is used to set up a file for reading and/or writing? code in python
Write a Python program that uses function(s) for writing to and reading from a file: a....
Write a Python program that uses function(s) for writing to and reading from a file: a. Random Number File Writer Function Write a function that writes a series of random numbers to a file called "random.txt". Each random number should be in the range of 1 through 500. The function should take an argument that tells it how many random numbers to write to the file. b. Random Number File Reader Function Write another function that reads the random numbers...
1.What standard methods can you use when handling file-reading and file-writing operations? a. Java b. Fragment-based...
1.What standard methods can you use when handling file-reading and file-writing operations? a. Java b. Fragment-based methods c. onClick d. DDMS 2. What would this query return? SELECT * FROM Items WHERE OrderDate >= Date('Now') a. All items in the database. b. Nothing c. Items that were ordered yesterday d. Items that were ordered today. 3. What can you use to manage files within a desired directory and create subdirectories? a. Subdirectory objects b. Directory class c. File objects d....
which tips about reading and writing from the readings have you used specifically in your writing...
which tips about reading and writing from the readings have you used specifically in your writing process?
in python You will be writing a program that can be used to sum up and...
in python You will be writing a program that can be used to sum up and report lab scores. Your program must allow a user to enter points values for the four parts of the problem solving process (0-5 points for each step), the code (0-20 points), and 3 partner ratings (0-10) points each. It should sum the points for each problem-solving step, the code, and the average of the three partner ratings and print out a string reporting the...
in java File encryption is the science of writing the contents of a file in a...
in java File encryption is the science of writing the contents of a file in a secret code. Write an encryption program that works like a filter, reading the contents of one file, modifying the data into a code, and then writing the coded contents out to a second file. The second file will be a version of the first file, but written in a secret code. Although there are complex encryption techniques, you should come up with a simple...
Consider the TCP connection mechanism.    i. What mechanism is used to set up a TCP...
Consider the TCP connection mechanism.    i. What mechanism is used to set up a TCP connection? ii. Why is the mechanism needed? iii. Outline how the mechanism works with a diagram. iv.CLASSFULL AND CLASSLESS IP
This assignment asks you to set up an Excel budget spreadsheet file that automatically prepares the...
This assignment asks you to set up an Excel budget spreadsheet file that automatically prepares the master budget for a company, given sales projections and information on beginning balances, production requirements, desired ending inventories, etc. Information on developing the budgets appears in Chapter 8 of your text, and examples of budget worksheets appear in the schedules throughout the chapter. Data Glamour Inc. produces and sells lady handbags. Below is information on its activities for the next few months. Sales projections...
Set up an integral that uses the disk method to find the volume of the solid...
Set up an integral that uses the disk method to find the volume of the solid of revolution obtained by revolving the area between the curves y = sech(x/2), y =2, x =0 and x = 4 around the line y=2. Include a sketch of the region and show all work to integrate and. Note: Recall that sech(u) = 1/cosh(u). Please show details for every single step
Set up a spreadsheet that implements the secant method and then solves each of the problems....
Set up a spreadsheet that implements the secant method and then solves each of the problems. Use the graph of each function to select an initial guess. Recall the iteration formula for the secant method: X^k+1=x^k-[f(x^k)/f(x^k)-f(x^k-1)](x^k-x^k-1) Put the formula for the function under the heading f(xk-1) and f(xk). In the cell under xk+1, put the secant method iteration formula. In the second row, replace the previous xk-1 with xk and then xk with xk+1. Now copy the two formulas down...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT