Curriculum
In Java, input and output (I/O) operations are performed using the java.io
package, which provides a set of classes and methods for reading data from input sources and writing data to output destinations. Here are some examples of how to use input and output in Java:
To read input from the user, you can use the Scanner
class, which provides methods for reading different data types. Here is an example of how to read a string from the user:
import java.util.Scanner; public class ReadInput { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter your name: "); String name = scanner.nextLine(); System.out.println("Hello, " + name + "!"); } }
In this example, we create a new Scanner
object to read input from the standard input stream (System.in
). We then use the nextLine()
method to read a line of text from the user and store it in a String
variable called name
.
To write output in Java, you can use the System.out
object, which represents the standard output stream. Here is an example of how to write a message to the console:
public class WriteOutput { public static void main(String[] args) { System.out.println("Hello, World!"); } }
In this example, we use the println()
method of the System.out
object to write a message to the console.
To read and write files in Java, you can use the File
and FileReader
or FileWriter
classes. Here is an example of how to read the contents of a file and write them to another file:
import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class FileIO { public static void main(String[] args) { try { File inputFile = new File("input.txt"); FileReader reader = new FileReader(inputFile); int ch; StringBuilder content = new StringBuilder(); while ((ch = reader.read()) != -1) { content.append((char) ch); } reader.close(); File outputFile = new File("output.txt"); FileWriter writer = new FileWriter(outputFile); writer.write(content.toString()); writer.close(); System.out.println("File copied successfully!"); } catch (IOException e) { e.printStackTrace(); } } }
In this example, we create a File
object to represent the input file, and a FileReader
object to read the contents of the file. We then use a StringBuilder
object to build a String
containing the contents of the file. We create another File
object to represent the output file, and a FileWriter
object to write the contents of the StringBuilder
to the file. We then close the input and output streams, and print a message to the console indicating that the file was copied successfully.