This article is participating in the Java Theme Month – Java Debug Notes Event, see the event link for details
Question: How do I join two arrays in Java
What is the easiest way to create and write (text) files in Java?
Answer:
Note that each of the following code examples may throw an IOException. The try/catch/finally block is omitted for simplicity. See this tutorial for information about exception handling.
Note that each code example below overwrites this file (if it already exists)
Create a text file:
PrintWriter writer = new PrintWriter("the-file-name.txt", "UTF-8");
writer.println("The first line");
writer.println("The second line");
writer.close();
Copy the code
Create a binary file:
byte data[] = ...
FileOutputStream out = new FileOutputStream("the-file-name");
out.write(data);
out.close();
Copy the code
Java 7+ users can use the Files class to write Files:
Create a text file:
List<String> lines = Arrays.asList("The first line", "The second line");
Path file = Paths.get("the-file-name.txt");
Files.write(file, lines, StandardCharsets.UTF_8);
//Files.write(file, lines, StandardCharsets.UTF_8, StandardOpenOption.APPEND);
Copy the code
Create a binary file:
byte data[] = ...
Path file = Paths.get("the-file-name");
Files.write(file, data);
//Files.write(file, data, StandardOpenOption.APPEND);
Copy the code
In Java 7 and later:
try (Writer writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("filename.txt"), "utf-8"))) {
writer.write("something");
}
Copy the code
The article translated from kgs4h5t57thfb6iyuz6dqtun5y ac4c6men2g7xr2a – stackoverflow – com. Translate. Goog/questions / 2…
The author suggests: the high score answer here is simply a simple implementation
As you can see, The Performance of FileChannel is relatively high. Briefly, take rocketMQ, which is a popular file system for storing data, producing and consuming data as directly manipulated files, It involves page caching, FileChannel, and FileChannel reading a page of 4KB at a time, thanks to ByteBuffer buffers and MMAP memory mapping
RokcetMQ has also been tuned for better performance
- Pre-allocated MappedFile
- Mlock system call
- File preheating
- Read and write sequentially
I’m just doing a piece here, everybody come on!
Thank you for reading this, if this article is well written and if you feel there is something to it
Ask for a thumbs up 👍 ask for attention ❤️ ask for share 👥 for 8 abs I really very useful!!
If there are any mistakes in this blog, please comment, thank you very much! ❤ ️ ❤ ️ ❤ ️ ❤ ️