In Rust, the equivalent of Java’s PrintWriter
is the std::io::Write
trait, which is implemented by a number of types that can be used to write data to an output stream, such as a file or a network socket.
To use Write
to write text to an output stream, you can use the write_all
method, which takes a byte slice as an argument and writes it to the output stream.
You can convert a string
to a byte
slice using the as_bytes
method.
Here is an example of how you might use Write to write text to a file:
use std::fs::File;
use std::io::Write;
fn main() -> std::io::Result<()> {
let mut file = File::create("output.txt")?;
file.write_all(b"Hello, world!")?;
Ok(())
}
If you want to use a buffered writer, similar to PrintWriter
, you can use the BufWriter
type from the std::io::BufWriter
module.
This type wraps a Write
implementation and buffers the output, improving performance by reducing the number of calls to the underlying write operation.
Here is an example of how you might use BufWriter
to write text to a file:
use std::fs::File;
use std::io::{BufWriter, Write};
fn main() -> std::io::Result<()> {
let file = File::create("output.txt")?;
let mut writer = BufWriter::new(file);
writer.write_all(b"Hello, world!")?;
writer.flush()?;
Ok(())
}
You can also use the writeln!
macro from the std::fmt
module to write a line of text to an output stream.
This macro takes a Write
implementation and a format string as arguments, and writes the formatted string to the output stream followed by a newline character.
Here is an example of how you might use writeln!
to write a line of text to a file:
use std::fs::File;
use std::io::Write;
fn main() -> std::io::Result<()> {
let mut file = File::create("output.txt")?;
writeln!(file, "Hello, world!")?;
Ok(())
}