In Java how to assign value to System.in? [duplicate] - java

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Writing data to System.in
We know that System.in (Standard Input) is connected to console. So whenever we write in console it will flow to this stream. But is there any way to pass value to this Standard Input without entering from console, i.e. like System.in = "ABCD". I just want to imitate as the value is passing from console.

Yes, there is. Use System.setIn(InputStream in).
You can supply any subtype of InputStream as well, so if you want to supply a specific value, you can use the StringBufferInputStream, like so:
StringBufferInputStream s = new StringBufferInputStream("ABCD");
System.setIn(s);

I think that instead of having your method directly access System.in:
public void process() {
byte b[] = new byte[4000];
int bytesRead = System.in.read(b);
...
}
You should factor that out so that an input stream is passed into the method:
public void run() {
process(System.in);
}
public void process(InputStream is) {
byte b[] = new byte[4000];
int bytesRead = is.read(b);
...
}
This gives you the same behavior, but lets you invoke the business logic with input streams of your own devising for test purposes, too.

Related

C# code passing void as argument? What's that in Java? [duplicate]

This question already has answers here:
C# Lambda ( => ) [duplicate]
(4 answers)
Closed 6 years ago.
I'm translating a small program from C# to Java.
There's 1 line left that I'm wondering about:
Thread eventReadingThread = new Thread(() => ReadEvents(url, streamingMode));
...
static void ReadEvents(String serviceURL, bool streamingMode)
{
if (streamingMode)
{
WebRequest httpClient = WebRequest.Create(serviceURL);
httpClient.Method = "GET";
byte[] buffer = new byte[4096];
...
I interpret the first line here as "True if ReadEvents returns less than empty array". However it doesn't make any sense, both because void arguments don't compile and because a boolean argument doesn't fit the constructor for Thread.
What would this be in Java?
What would it be in Java?
In Java 8 you just turn => to ->.
{
Thread thread = new Thread(() -> readEvents(url, streamingMode));
}
static void readEvents(String serviceUrl, boolean streamingMode) {
// ...
}
I interpret the first line here as .... What is the code trying to do?
You need to read up on lambda expressions (Java, C#). In this case it is "create me a Runnable or ThreadStart that calls the method readEvents.
First,
static void ReadEvents
does not mean ReadEvents returns true under any circumstances. The void keyword means that the method has no return (like a Sub in VB).
Second, you define your array as:
byte[] buffer = new byte[4096];
The default value for byte is 0, so you never actually have an empty array, you instead, have an array of 4096 bytes with the value 0. Unless somewhere further in the code (which you are not showing) you redefine the array as byte[] or null.

IllegalStateException - no last call on a mock available

I'm trying to use EasyMock to test that a method runs a specific number of times but I keep getting an IllegalStateException error and I don't understand why. I'm new to EasyMock and JUnit and not very familiar with how to use them so I'm not sure what I'm doing wrong.
My code is:
FileOutputStream mockWriter;
Numbers mockByte;
#Test
public void testNumbers() throws IOException{
mockWriter = createMock(FileOutputStream.class);
mockByte = new Numbers(mockWriter);
mockByte.initByte();
expect(mockByte.generate()).times(10000);
replay(mockWriter);
}
And these are the methods initByte and generate from my Numbers class:
public void initByte() throws IOException{
File outFile = new File("NumbersOutput.txt");
FileOutputStream f = new FileOutputStream(outFile);
for(int i = 0; i < 10000; i++){
int b = generate();
f.write(b);
}
f.flush();
f.close();
}
public int generate(){
return rand.nextInt(100001);
}
The error you're getting is because nothing's calling anything on your mock.
Contrary to your naming, mockByte doesn't refer to a mock at all, so using it in an expect call like this is not going to help you. You should be expecting calls on mockWriter if anything.
However, it's not clear why you're using a mock for a stream at all, nor what the OutputStream in the Numbers constructor is used for. Your initByte() method doesn't use any state within the object other than rand. Even when that's fixed, it would probably be simplest just to use a ByteArrayOutputStream... make your API talk in terms of OutputStream instead of FileOutputStream, and it'll be much easier to test.
I suspect you should:
Remove the construction of a new FileOutputStream from the initByte method, instead writing to the stream you accept in the Numbers constructor
If your constructor parameter type is FileOutputStream, change it to OutputStream to make it cleaner and easier to test
Create a ByteArrayOutputStream in your test - you don't need mocking at all. You can then get all the bytes that have been written, and check them for whatever you want.
Think carefully about what you expect f.write(b) to do. It's only going to write a single byte, so the top 24 bits of your random number are going to be ignored. At that point, why are you choosing a number in the range [0, 10000] anyway?

Using BufferedReader

I am doing a method involving BufferedReader and I to have use it as an input argument, can someone tell me how to use it as an input argument but initialize it outside the method?
Other thing is, how do I get the buffer to read special characterS? (eg: ยด, ~)
public static List<Pacote<Pair<String, Double>>> create(
BufferedReader fileReader, int capacidadePacotes)
throws IOException {
List retorno = new ArrayList <> (6);
String s;
while ((s=fileReader.readLine())!=null){
retorno.add(parseItem(s));
}
return retorno;
}
It basically reads a file and sends it to another function that treats the text and creates objects based on that, I'm just not clear on the whole using BufferedReader as an input argument, have just used it inside the method before so I'm unclear on how to initialize it properly, probably a dumb question but I would like to know how to do it properly
You can initialize the BufferedReader object as follows if you are trying to read a file.
public static void main(String[]args) {
BufferedReader rdr = new BufferedReader(new FileReader("filepath"));
int capacidadePacotes = 10;
create(rdr, capacidadePacotes);
}
//urcode for create
The buffered reader can read line by line using the readLine() method. If you read null that means you reached the end of the file. A more readable way to use the buffered reader would be the following:
String s = rdr.readLine();
while(s != null) { //while u didn't reach the end of the file
//your code
s = rdr.readLine();
}
If you want to initialize it "outside" the method, why not hand it over like that:
create(new BufferedReader(reader, 3));
Or how exactly do you want it to have instantiated? For the instantiation, you need a Reader, which can be handed over. If you want to create a Reader from a file, the answer is also in the following link.
How to read special characters with a BufferedReader:
Read special characters in java with BufferedReader

replace a string segment from input stream

I am trying to receive a huge text file as an inputstream and want to convert a string segment with another string. I am strictly confused how to do it, it works well if I convert whole inputstream as a string which I don't want as some of the contents are lost. can anyone please help how to do it??
e.g.
if I have a file which has the contents "This is the test string which needs to be modified". I want to accept this string as input stream and want to modify the contents to "This is the test string which is modified" , ( by replacing 'needs to be' with is).
public static void main(String[] args) {
String string = "This is the test string which needs to be modified";
InputStream inpstr = new ByteArrayInputStream(string.getBytes());
//Code to do
}
In this I want the output as: This is the test string which is modified
Thanking you in advance.
If the text to be changed will always fit in one logical line, as I stated in comment, I'd go with simple Line Reading (if applyable) using something like:
public class InputReader {
public static void main(String[] args) throws IOException
{
String string = "This is the test string which needs to be modified";
InputStream inpstr = new ByteArrayInputStream(string.getBytes());
BufferedReader rdr = new BufferedReader(new InputStreamReader(inpstr));
String buf = null;
while ((buf = rdr.readLine()) != null) {
// Apply regex on buf
// build output
}
}
}
However I've always like to use inheritance so I'd define this somewhere:
class MyReader extends BufferedReader {
public MyReader(Reader in)
{
super(in);
}
#Override
public String readLine() throws IOException {
String lBuf = super.readLine();
// Perform matching & subst on read string
return lBuf;
}
}
And use MyReader in place of standard BufferedReader keeping the substitution hidden inside the readLine method.
Pros: substitution logic is in a specified Reader, code is pretty standard.
Cons: it hides the substitution logic to the caller (sometimes this is also a pro, still it depends on usage case)
HTH
May be I understood you wrong, but I think you should build a stack machine. I mean you can use a small string stack to collect text and check condition of replacement.
If just collected stack already is not matched to your condition, just flush stack to output and collect it again.
If your stack is similar with condition, carry on collecting it.
If your stack is matched your condition, make a modification and flush modified stack to output.

Java InputStream != Readable

I am using java.util.Scanner for things such as nextInt(), and all was working fine as long as I was using a java.lang.Readable (one and only constructor argument). However, when I changed to using an InputStream instead, Scanner.nextInt() never returns. Do you know why?
My implementation of the InputStream looks like this:
private static class ConsoleInputStream extends InputStream {
...
private byte[] buffer;
private int bufferIndex;
public int read() throws IOException {
...
while (...) {
if (buffer != null && bufferIndex < buffer.length) {
return buffer[bufferIndex++]; // THE COMMENT!
}
...
}
...
}
}
When I print the data by THE COMMENT I (correctly) get stuff like '1','2','\n' for "12\n", etc. Is there some Scanner hookup, unbeknown to me, that cause this behavior?
From the javadocs for InputStream's read() method:
"Returns: the next byte of data, or -1 if the end of the stream is reached."
I would guess that you're never returning -1?
I think the problem is with your self-built InputStream. Why did you build your own, rather than simply simply using System.in ?
Update:
Wanted input from a JTextField.
OK, got it. It usually doesn't make sense to use I/O handling to read stuff that's already available, in character form, but I can see how that would make your life easier with Scanner.
Still, you could probably have saved yourself some coding and grief by using a "finished" InputStream. What comes to mind is
InputStream is = new ByteArrayInputStream(myTextField.getText().getBytes());
Java I/O is yucky. Be glad the bright people from Sun have encapsulated most of it away for you.

Categories