The following example shows how to write a file using Java NIO. It
creates a file named loginlist.txt, if the file already exists then it
will remove it. The following code also generate random strings of arbitrary length. The strings are written in the following format :-
<Random Strings> : <Random Strings>
It writes 10 million entries and takes 32 seconds in my PC (Intel Core i3 2nd Gen, RAM - 4 GB) to complete and file size reaches to about 180 MB.
<Random Strings> : <Random Strings>
It writes 10 million entries and takes 32 seconds in my PC (Intel Core i3 2nd Gen, RAM - 4 GB) to complete and file size reaches to about 180 MB.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package files; | |
import java.io.BufferedWriter; | |
import java.io.IOException; | |
import java.nio.charset.Charset; | |
import java.nio.file.Files; | |
import java.nio.file.Path; | |
import java.nio.file.Paths; | |
import java.util.Random; | |
/** | |
* | |
* @author psycho_coder | |
*/ | |
public class WriteFileUsingJavaNIO { | |
private static final String CHARLIST = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; | |
private static int DEF_STRING_LEN; | |
private static Random rand = null; | |
public WriteFileUsingJavaNIO() { | |
rand = new Random(); | |
DEF_STRING_LEN = 8; | |
} | |
/** | |
* This method generates random string | |
* | |
* @param len Length of Random string to be generated. | |
* @return returns a Randon String of size len. | |
*/ | |
private String generateRandomString(int len) { | |
int RAND_STRING_LEN = len > 0 ? len : DEF_STRING_LEN; | |
StringBuilder randStr = new StringBuilder(); | |
for (int i = 0; i < RAND_STRING_LEN; i++) { | |
int number = rand.nextInt(CHARLIST.length()); | |
char ch = CHARLIST.charAt(number); | |
randStr.append(ch); | |
} | |
return randStr.toString(); | |
} | |
public static void main(String... string) throws IOException { | |
Path path = Paths.get(System.getProperty("user.dir"), "src", "data", "loginlist.txt"); | |
System.out.println(path.toAbsolutePath()); | |
if (Files.isWritable(path) && !Files.isDirectory(path)) { | |
Files.deleteIfExists(path); | |
path = Files.createFile(path); | |
} | |
WriteFileUsingJavaNIO obj = new WriteFileUsingJavaNIO(); | |
try (BufferedWriter buff = Files.newBufferedWriter(path, Charset.defaultCharset())) { | |
for (int i = 1; i < 10000000; i++) { | |
buff.append(obj.generateRandomString(DEF_STRING_LEN) + ":" | |
+ obj.generateRandomString(DEF_STRING_LEN)); | |
buff.newLine(); | |
buff.flush(); | |
} | |
} | |
} | |
} |