Null pointer Exception while decrypting - java

im using a function called decrypt to decrypt my encrypted strings in a file using the bufferedreader but the problem is when i use the function it throws NullPointerException, can any one help me? Thanks in advance!
This is my functon:
public String Decrypt (String Word,int key)
{
String result="";
for (int i=0;i<Word.length();i++)
{
result+=(char)(Word.charAt(i)-key);
}
return result;
}
bufferedreader code:
try {
BufferedReader out=new BufferedReader(new FileReader("array.txt"));
String line="";
while((line=Decrypt(out.readLine(), 30)) !=null) // unknown exception
{
output.append("Your String is: \n"+ line);
}
}catch (FileNotFoundException ex) {
} catch (IOException ex) {
}

This is not clean:
while((line=Decrypt(out.readLine(), 30)) !=null)
We know that readline will return null when the BufferedReader reaches the end of the stream as per the BufferedReader API, but your code does not properly handle this, namely your Decrypt method will call call the length() method on the Word parameter whether or not it is null. I suggest that you not try to make your code too brief and instead separate out the reading of the Reader from acting on it. e.g.,
while((line= out.readLine) !=null) {
line = Decrypt(line, 30);
output.append("Your String is: \n"+ line);
}
As an aside, you will want to learn and use Java naming conventions. Variable names should all begin with a lower letter while class names with an upper case letter. Learning this and following this will allow us to better understand your code, and would allow you to better understand the code of others.
Aside 2: don't leave your exception's catch blocks empty as this is the Java equivalent of driving your car with youer eyes closed. At least print out the stack trace and definitely check out the Exceptions Tutorial

Related

Java Socket.readLine() not always reading whole message separated by newLine

readLine() works fine in many cases but few times, the line I read in by BufferedReader.readLine() is incomplete line. This question talks about similar issue. However the solutions are not satisfactory. A solution there says that it maybe because of EOF character. But in my case I am not sending any EOF character at all. Below are my codes:
/*Sending Code*/
public void sendToLocalDaemon(String msg){/*msg have no New line or \r*/
localMachineWriter.println(msg);
}
/*Receiving Code*/
public int receiveFromCoordinator(){
String response = "";
while(true){/*Each message separated from new line will have its independent meaning.*/
try{
coordinator.setSoTimeout(1);
try{
response = coordinatorReader.readLine();
}
catch(java.net.SocketTimeoutException e){
response = null;
}
if(response == null){
return coordinatorsMessage.size();
}
coordinatorsMessage.add(response);
}
catch(IOException e){
log(e.getMessage());
//System.exit(0);
}
}
}
/*This is how I set reader and writer*/
public void setReaderWriter() throws IOException{
this.coordinatorWriter = new PrintWriter(coordinator.getOutputStream(),true);
this.coordinatorReader = new BufferedReader(new InputStreamReader(coordinator.getInputStream()));
}
Please either suggest me someway to make this work correctly. Or suggest me some other way by which I can read whole message, with 100% guarantee.
The problem is your read timeout. If it happens, you can lose data. If readLine() times out in the middle of a line, the part read so far is lost. If you set it too short, you will lose a lot of data, and you're setting it much too short. You should set it much higher, or not use one at all.

Strange behavior of EOFException

I have some simple class that is DataInputStream stream to read from file.
I have surrounded this stream with EOFException try-catch block.
It has some strange behavior coz sometimes it throws EOFException into text that is read.
Output to console:
"The vessel was in as good condition as I am, and as, I hope
you ar#End of streame#, M. Morrel, and this day and a half was lost from
pure whim, for the pleasure of going ashore, and nothing
else."
I couldn't figure out what is cause of this strange behavior...
Here is code snippet:
public class FormattedMemoryInput {
public static void main(String[] args) throws IOException {
boolean done = false;
try (DataInputStream in = new DataInputStream(new ByteArrayInputStream(
BufferedInputFile.read("./gutenberg/cristo.txt").getBytes()));) {
while (!done) {
System.out.print((char) in.readByte());
}
} catch (EOFException e) {
System.err.println("#End of stream#");
}
}
}
It uses static method BufferedInputFile.read() to read first 500 lines:
public class BufferedInputFile {
// Throw exceptions to console:
public static String read(String filename) throws IOException {
// Reading input by lines:
BufferedReader in = new BufferedReader(new FileReader(filename));
StringBuilder sb = new StringBuilder();
String s;
int i = 0;
while ((s = in.readLine()) != null && (i < 500)) {
sb.append(s + "\n");
i++;
}
in.close();
return sb.toString();
}
Why EOFException is thrown into text?
Solution:
It was at adding one line:
while (!done) {
System.out.print((char) in.readByte());
System.out.flush(); // this one
}
Well, you're getting an EOFException because you're reading forever - you never change the value of done.
The reason it's appearing in the middle of the text instead of at the end is that you're using System.err to print in the exceptional case, and System.out to print the main text. Those are separate streams, flushed separately. If you flush System.out before writing to System.err, I suspect you'll see the main text before the error message. (Note that you're using println on System.err, which will flush automatically, but just print on System.out, which won't.)
There are various other things I'd change about the code - particularly the use of String.getBytes() without specifying an encoding - but assuming I've understood your question correctly, the difference in streams is the reason you're looking for.
System.out is buffered by default; System.err isn't. If you redirect one of the output streams, either in your program or from the shell, you should see the output in the expected order. You can force System.out to print its output by calling System.out.flush();; try inserting that at the end of your while loop.

No output for recursive method

I have the following method to read a file and output its lines in reverse order:
public void Reverse(BufferedReader br, PrintWriter pw)
{
try
{
String headLine = br.readLine();
if (headLine != null)
{
Reverse(br, pw);
pw.println(br.readLine());
}//if
pw.println(headLine);
}//try
}//Reverse
For some reason, I am not seeing anything in the output file when the code is run It is compiling correctly though. Any ideas?
Firstly, your code won't even compile - you have a try block with no catch or finally block. When we can't see your real code, it's even harder than normal to know for sure what's going on.
Secondly, you're calling readLine() twice for no obvious reason, and then writing out headLine even if it's null. Shouldn't your code really be:
if (headLine != null)
{
Reverse(br, pw);
pw.println(headLine);
}
without the extra println afterwards?
My guess is that you're never flushing or closing the PrintWriter, and you've got auto-flush turned off. Don't do that. Or maybe there's an exception somewhere, which PrintWriter isn't going to report because it swallows them. Personally I'd recommend taking just a Writer or BufferedWriter instead of a PrintWriter, and declaring that Reverse can throw IOException. Then make sure that the calling code closes the writer in a finally block.
I'd also suggest not using recursion for this, unless you're just using this as a way of investigating recursion. It would be far saner to read the whole file into a list of strings, reverse it, then write it all out.
try this code:
public void Reverse(String headLine, BufferedReader br, PrintWriter pw) throws IOException
{
try
{
headLine = br.readLine();
if (headLine != null)
{
Reverse(headLine, br, pw);
pw.println(headLine);
}//if
//pw.println(headLine);
}finally {
}
}
here, initially send the headline as ""
Your original code try to write a newly-read line after all lines have already been read.
What you need is to write the headline value after calling Reverse again, like this:
public void Reverse(BufferedReader br, PrintWriter pw) throws IOException
{
String headLine = br.readLine();
if (headLine != null)
{
Reverse(br, pw);
pw.println(headLine);
}
}

How do I return a String in a try/catch statment?

I am trying to return a String from the following method.
public String openCon() {
try {
Scanner scan = new Scanner(System.in);
URL sitex = new URL("http://" + scan.nextLine());
URLConnection connection = sitex.openConnection();
Object content = sitex.getContent();
BufferedReader in = new BufferedReader(new InputStreamReader(sitex.openStream()));
String str;
String x = "1";
while ((str = in.readLine()) != null) {
x += str;
}
in.close();
return x;
}
catch(Exception e) {
System.out.println(e);
}
}
The problem isn't returning from the try block - the problem is that you aren't returning anything if an exception is thrown. You're catching the exception... but then reaching the end of the method without returning anything. (To put it in more technical terminology: the end of a non-void method should not be reachable.)
Personally, I would just remove the catch block entirely, and add throws declarations for any exceptions which are thrown within the body. You're not really handling the exceptions - you're just printing them out and ignoring them, which is very rarely a good idea. Catching Exception is usually a pretty bad idea to start with.
As an aside, you should also close your BufferedReader and URLConnection values in a finally block so they're closed even in the case of an exception. I'd also suggest either passing a fixed encoding name to InputStreamReader, or using a higher-level HTTP client API which will use the content-type header from the response. Oh, and use StringBuilder instead of string concatenation in a loop.
Why not initialise the variable before the try statement, and place the return statement after it?
If there's an exception before the return statement, the method won't return anything. Since you're not really handling the exception, I recommend you just let it bubble up and handle it at a higher level. This may be the main method if there's no better place. You will need to declare the method as throws IOException and possibly add other exception classes.
Also, use try-with-resources to ensure your instances (BufferedReader and InputStreamReader) are closed properly.
You should return something in the catch block, for example:
catch(Exception e) {
System.out.println(e);
return "";
}
Use:
String result = ""
try{
result = "OK";
}catch (Exception e){
result = e.toString();
}finally{
return result;
}

java equivelant to uix cut

i'm not a java coder but need a commnad that will do
cut -d "/" -f1,2,3 MyFile
Any ideas?
Read the file. Split each line on / and then print out the first three parts.
BufferedReader in = null;
try{
in = new BufferedReader(new FileReader("MyFile"));
String line = "" ;
while((line = in.readLine()) != null){
String[] fields = line.split("/");
System.out.printf("%s/%s/%s\n", fields[0], fields[1], fields[2]) ;
}
}
catch(Exception e){
e.printStackTrace();
}
finally{
if (in != null) {
try {
in.close();
} catch (IOException e) {
}
}
}
The main difference between Java coding and that script example is that they use different programming paradigm lest say that Java use Object Programing and that example can be assigned to declarative programing (You only express the logic, not the way to get the result) so no commands in Java.
So there is no command that You can use for this type of functionality.
There might be some package with this type of static procedure that works like that cut program. But still You will have to write a program to use it.
So if You would describe us the purpose of usage of this program (cut) )we could be able to provide You a good answer.

Categories