Skip to content

Instantly share code, notes, and snippets.

@justjanne justjanne/jes.java
Last active Jun 14, 2017

Embed
What would you like to do?
import java.io.FileDescriptor;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
public class Jes {
/**
* Maximum buffer size to be allocated
*/
private static final int BUFFER_SIZE = 8192;
/**
* Default value to be used if none given
*/
private static final String DEFAULT_VALUE = "y";
public static void main(String... args) throws IOException {
ByteBuffer buffer = getBuffer(BUFFER_SIZE, getArgument(DEFAULT_VALUE, args));
FileChannel open = FileChannel.open(Paths.get("/proc/self/fd/1"),
StandardOpenOption.APPEND, StandardOpenOption.WRITE);
while (true) {
open.write(buffer);
buffer.clear();
}
}
/**
* Creates a stack-allocated native buffer pre-filled with the given value, up to a certain size
*
* @param maxLength Maximum size the buffer should have
* @param value Value the buffer should be filled with
*
* @return The ByteBuffer that was filled
*/
private static ByteBuffer getBuffer(int maxLength, String value) {
ByteBuffer template = StandardCharsets.UTF_8.encode(value);
int templateLength = template.limit();
int amount = maxLength / templateLength;
ByteBuffer buffer = ByteBuffer.allocateDirect(amount * templateLength);
for (int i = 0; i < amount; i++) {
for (int j = 0; j < templateLength; j++) {
buffer.put(i * templateLength + j, template.get(j));
}
}
return buffer;
}
/**
* Builds the template string that should be repeated
*
* @param defValue Default value to be used if no arguments are given
* @param args Command line arguments given to the program
*
* @return A string containing all command line arguments, or, if none given, the default value.
*/
private static String getArgument(String defValue, String[] args) {
if (args.length > 0) {
StringBuilder builder = new StringBuilder();
for (String arg : args) {
builder.append(arg);
}
builder.append("\n");
return builder.toString();
} else {
return defValue + "\n";
}
}
}
@ArsenArsen

This comment has been minimized.

Copy link

commented Jun 13, 2017

Line 44: value.getBytes("UTF-8")

Any reason for using the charset manially?

EDIT: Oh, to get the native buffer. nvm

@ArsenArsen

This comment has been minimized.

Copy link

commented Jun 13, 2017

import sun.nio.ch.FileChannelImpl; With the release of JDK9, this import will not work, as you won't be able to access sun.* for some stupid reason.

@justjanne

This comment has been minimized.

Copy link
Owner Author

commented Jun 13, 2017

@ArsenArsen: Edited, now works also on JDK 9

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.