Why am I getting a null pointer access? [closed] - java

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
Why am I getting a
Null pointer access: The variable versionFromInputStream can only be null at this location
Error?
Is that because the IDE doesn't know about the read method?
byte[] versionFromInputStream = null;
if (input.read(versionFromInputStream, 0, 3) != 3)
{
throw new NetworkException();
}
double version = Double.parseDouble(versionFromInputStream.toString());

The read method of a stream expects an existing byte array with enough space to be passed. Also, the conversion of bytes to String ought to be done via the String(byte[]) constructor.
In this case, you are reading three bytes, so the following ought to suffice:
byte[] versionFromInputStream = new byte[3];
if (input.read(versionFromInputStream, 0, 3) != 3)
{
throw new NetworkException();
}
double version = Double.parseDouble(new String(versionFromInputStream));
From a design standpoint, you may want to avoid sending strings over a network as it's inefficient. As long as you have control over both the sender and the receiver, a DataInputStream/DataOutputStream will let you natively read and write integers to the stream, without the overhead of reading bytes and converting them to strings to be parsed. As a quick example showing the receive side (with an integer version):
DataInputStream dataInput = new DataInputStream(input);
int version = dataInput.readInt();
You'd need to adapt the sender to use a DataOutputStream accordingly.

So you've got a couple of things going on here that aren't right
byte[] versionFromInputStream = null; // you should initialize this like = new byte[2048]; because..
if (input.read(versionFromInputStream, 0, 3) != 3) // because here you are trying to read into this byte array. And because it hasn't been initialized, you are getting the exception
{
throw new NetworkException();
}
double version = Double.parseDouble(versionFromInputStream.toString()); // this isn't going to work either. byte[].toString is the same as Object.toString - it just prints out the location of the object in virtual memory, which isn't what you want

Related

Switching between file paths in Java [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I am writing a mergesort for an externalsort, which reads 2 chunks of data at a time from a file A, merges them into a larger chunk, and writes it to a file B. After this, I need to then read 2 of these increased chunks at a time from file B, merge them into 1 larger chunk, and write this to file A. This switching goes on until all the data counts as 1 chunk at the end.
I have tried swapping the identifiers around like this after each iteration:
RandomAccessFile temp = fileA;
fileA = fileB;
fileB = temp;
This requires, that I update the BufferedInput and BufferedOutputStreams with the new file directory names and construct them each time.
I have a limited amount of RAM, so I cannot keep creating new objects unless I have to. Is there a better way to switch the target file and source file each iteration?
A simple generic Swapable class should allow you to swap between two objects.
class Swapable<T> {
final T a;
final T b;
boolean useA = true;
Swapable(T a, T b) {
this.a = a;
this.b = b;
}
T get() {
return useA ? a : b;
}
void swap() {
useA = !useA;
}
}
Create your two RandomAccessFiles and install them in a Swapable. Use the get method to get the current file. Use the swap method to switch between them.

is there a bug in java new String [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 7 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
I try this code:
byte[] data = new byte[66000];
int count = is.read(data);
String sRequest = new String(data); //will received byte array hello
String all = sRequest;
all = all.concat("world");
System.out.println(all);
It only print to my console: hello
concat funtion of java have bug? I also used + operator instead concat function but result same :(
How can I concat a String with new String from a byte array?
Instead of
String sRequest = new String(data); //will received byte array hello
use
String sRequest = new String(data, 0, count); //will received byte array hello
You will notice the difference when you additionally print the length of the result string:
System.err.println(all + "/" + all.length());
gives helloworld/66005 in the first case and helloworld/10 in the second case. The reason you only see "hello" might be an issue of your console - in Eclipse, I do see "helloworld" but when I copy&paste that into another editor only one of the words is taken. The 0 values from the initial array are part of the result (since they already had been added to the first string), but they are not printed out (since they are not printable characters).

java process memory increase with new Strings and byte[] created? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
We added a new feature in our web application that has the the following code, basically decompressing the inputstream and creating a new String with UTF-8 encoding
....
// is is an instance of java.util.zip.GZIPInputStream
byte[] payloadBuf = org.apache.commons.compress.utils.IOUtils.toByteArray(is);
String plainPayload = new String(payloadBuf, CharEncoding.UTF_8);
...
when we run an intensive load test that triggers this path many times, we see an abnormal increase of not-heap memory in JVM. Can anyone give some hint on interpreting this? And even better, is there a way to avoid it somehow? Thanks a lot
There is nothing abnormal about your results:
If you call this code in a tight loop you are creating lots and lots of short lived objects. 3 byte[] instances ( all Objects ) as well as a ByteArrayStream for every call! And for no reason apparently.
So you are creating and copying a bunch of byte[] instances around and then the String constructor creates at least one more byte[] and copies that as well, all for nothing.
Are not accomplishing what you think you are doing:
You are not creating a new String with UTF-8 encoding, you are creating a new String which is interpreting the byte[] as UTF-8.
Java stores all String objects in memory as UTF-16, so you are not creating a new String with UTF-8 encoding.
Solution:
You should just read the file into a String to begin with and be done with it, you are creating this intermediate byte[] for nothing!
Here is a couple of examples using Guava:
final String text = CharStreams.toString(new InputStreamReader(is,Charsets.UTF_8));
or
final ByteSource source ...
final String text = source.asCharSource(Charsets.UTF_8).read();
Opinion:
That org.apache.commmons stuff is crap with all the cancerous dependencies and it is not doing anything special to begin with and still makes you deal with a checked exception on top of it all!
165 public static byte[] toByteArray(final InputStream input) throws IOException {
166 final ByteArrayOutputStream output = new ByteArrayOutputStream();
167 copy(input, output);
168 return output.toByteArray();
169 }
If you follow the rabbit hole you will find out that one call to .toByteArray() creates at least 3 instances of byte[] objects, a couple of ByteArrayStream objects that all end up as garbage just to get to String.

Java function for number of colons in a CSV file [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 9 years ago.
Improve this question
What function should i use for Java programming to get the total number of colons in a CSV file?
PS: not a Java developer.
Read the file char by char (using a BufferedReader to make it fast), and count each colon you meet:
int countColons() throws IOException {
try (BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(file.txt), "UTF-8"))) {
int count = 0;
int c;
while ((c = in.read()) >= 0) {
if (c == ':') {
count++;
}
}
return count;
}
}
Of course, you should use the appropriate encoding for your file. Not necessarily UTF-8.
Read the file line by line. For every line, use replaceAll to get rid of every character that isn't a colon. Then get the length of the resulting String. Keep a cumulative total of the results of this.
If you don't want to reinvent the wheel:
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
int count = StringUtils.countMatches(FileUtils.readFileToString(new File("file.csv")), ":");
One cool trick I found a while ago for counting the number of occurences is to take the length of the string, and minute all the values from it that are not your desired value.
Example
// Assume fileStr contains everything in the file
int numberOfColons = fileStr.length() - fileStr.replaceAll(":", "").length();
This will give you the number of colons in the file.
Edit
Just remembered when I got it from. It is from this question.
The reason why I like this approach
Obviously, it's extremely short, which is always nice. It does give some of a hit to the processor, but it avoids all loops (in your code at least) and it seems like a very elegant solution to the problem.

Java convert bytes (in the form of a string) into a string [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm receiving a string of bytes from my server like so:
60,104,101,97,100,62,60,115,99,114,105,112
How can i convert this into a readable string?
This is what I've tried to do:
String s = new String(json.get("msg").toString());
System.out.println("Text Decryted : " + s);
But this just gives me:
60,104,101,97,100,62,60,115,99,114,105,112
Any ideas how to accomplish this?
Parse a byte array from it:
String byteString = "60,104,101,97,100,62,60,115,99,114,105,112";
String[] byteStrings = byteString.split(",");
byte[] bytes = new byte[byteStrings.length];
for (int i = 0; i < bytes.length; i++) {
bytes[i] = (byte)Integer.parseInt(byteStrings[i]);
}
Then interpret the bytes as a string in a particular character set. Find out which character set you're actually using, to avoid future problems.
String string = new String(bytes, java.nio.charset.StandardCharsets.UTF_8);
The above is not very efficient by the way. Since you're already sending a string from the server, it would make more sense just to send the actual string. If you can't send the string as-is, you should ask about that problem.

Categories

Resources