package org.code2care.streams;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.stream.Stream;
public class WriteToFileStreamAPIExample {
public static void main(String[] args) {
String line1 = "This is line 1.";
String line2 = "This is line 2.";
String line3 = "This is line 3.";
String line4 = "This is line 4.";
Stream<String> stream = Stream.of(line1, line2, line3, line4);
String fileName = "myfile.txt";
Path filePath = Path.of(fileName);
try {
Iterable<String> iterable = stream::iterator;
Files.write(filePath, iterable, StandardOpenOption.CREATE);
} catch (IOException e) {
System.out.println("Error while writing to file: " + e.getMessage());
}
}
}
Facing issues? Have Questions? Post them here! I am happy to answer!
More Posts related to Java,
- Deep Dive into Java 8 Predicate Interface
- Read and Parse XML file using Java DOM Parser [Java Tutorial]
- Java 8 Predicate Functional Interface isEqual() Method Example
- Convert Multidimensional Array toString In Java
- How to read int value using Scanner Class Java
- Spring Boot AI + LLM + Java Code Example
- Write to a File using Java Stream API
- Implementing Bubble Sort Algorithm using Java Program
- How to Fix XmlBeanDefinitionStoreException in Java SpringBoot ApplicationConfig.xml
- YAML Parser using Java Jackson Library Example
- [Fix] java: integer number too large compilation error
- Convert JSON String to Java GSON Object Example
- Read a file using Java 8 Stream
- Java Spring Boot 3 Web Hello World with Gradle in IntelliJ
- Ways Compare Dates in Java Programming with Examples
- Pretty Print JSON String in Java Console Output
- Java JDBC with Join Queries Example
- How to Check For Updates on Windows 11 (Step-by-Step)
- [Fix] java.net.MalformedURLException: unknown protocol
- How to display date and time in GMT Timezone in Java
- Error: LinkageError occurred while loading main class UnsupportedClassVersionError [Eclipse Java]
- How to convert a String to Java 8 Stream of Char?
- RabbitMQ Queue Listener Java Spring Boot Code Example
- 5+ Fibonacci number Series Java Program Examples [ 0 1 1 2 3 ..]
- Handling NullPointerException with Java Predicate
More Posts:
- Shortcut: Move Cursor at the start or end of Line or file in Visual Studio Code (VS Code) - Shortcuts
- Fix- Microsoft Word Pages Appear Black - Microsoft
- Create SharePoint list from Excel spreadsheet and import table - SharePoint
- Android : Exception raised during rendering: action_bar API 22 - Android
- How to Toggle Dark and Light Mode on macOS Sonoma 14 - MacOS
- error CAML Query containing special characters - SharePoint
- Stop Automatic Opening of Music App on Mac when I connect Earphones - MacOS
- Bash Commands to Display File Contents - Bash