import java.io.FileWriter; import java.io.IOException; public class Example1 { public static void main(String[] args) { try { FileWriter writer = new FileWriter("output.txt"); writer.writeString("This is a sample string"); writer.close(); } catch (IOException e) { e.printStackTrace(); } } }
import java.io.OutputStream; import java.net.Socket; public class Example2 { public static void main(String[] args) { try { Socket socket = new Socket("localhost", 8080); OutputStream outputStream = socket.getOutputStream(); outputStream.writeString("Hello world"); socket.close(); } catch (IOException e) { e.printStackTrace(); } } }In this example, we are creating a socket connection to a server running on the local machine on port 8080. We are then getting the output stream of the socket to write data to the server. We are using the writeString() method to write the string "Hello world" to the server. Finally, we are closing the socket connection. This example can be useful for sending data over a network connection. The package library used here is java.net.