:sad: Hi ,I have a text file and it contains a message ,I want to extract the last four characters in this file and then convert it to integer i did the following:
FileInputStream Received_Message=new FileInputStream ("MyFile.txt");
BufferedReader buff2=new BufferedReader(new InputStreamReader(Received_Message));

System.out.println("Your Received message is as following:");
while((recv_Message=buff2.readLine() )!=null){
System.out.println(recv_Message);
}

four_characters=recv_Message.substring(recv_Message.length() - 4);
Four_characters_Integers = Integer.parseInt(four_characters);
i sure have try and catch and defined all varibles above
but the problem it gives me this message when i use this statement:
four_characters=recv_Message.substring(recv_Message.length() - 4);
the Exception is as following:
java.lang.NumberFormatException: null
at java.lang.Integer.parseInt(Integer.java:373)
at java.lang.Integer.parseInt(Integer.java:454)
at final_append.CopyBytes.main(CopyBytes.java:101)
Exception in thread "main"
how can i solve this??plz any help in

Recommended Answers

All 14 Replies

Member Avatar for iamthwee
/*
 * Pedantic.java
 *
 * 
 */

class Pedantic
{
    
  public static void main (String [] args) 
 { 
     String crap = "blah blah blah blah 2343";
     int length = crap.length();
     String c = crap.substring(length-4,length);
     int num = Integer.parseInt(c);
     System.out.println(num*2); //multiply by 2
  }

}

Actually I suspect it's something else. Hmm, are you sure the last four characters are in your file are definitely numbers?

System.out.println("Your Received message is as following:");
while((recv_Message=buff2.readLine() )!=null){
System.out.println(recv_Message);
}

four_characters=recv_Message.substring(recv_Message.length() - 4);
Four_characters_Integers = Integer.parseInt(four_characters);

I haven't tried it, I would, however, assume that recv_Message is null
at the point where you try to get the last four characters, as your
while loop will not exit until it is. Try this:

String last = "";
System.out.println("Your Received message is as following:");
while((recv_Message=buff2.readLine() )!=null){
  last = recv_Message;
  System.out.println(recv_Message);
}

four_characters=last.substring(last.length() - 4);
Four_characters_Integers = Integer.parseInt(four_characters);

Well, the JVM is telling you that the last 4 characters of your string are not a number. So....

hi how could this happen if my message was as following:
5113350515586806264156901277970003516182249744328267808527911381008517422384937086806339111024080220
and it prints it ...so the last four caharcters are really numbers but it still gives me the same exception when i write the statement:
c = recv_Message.substring(length2-4,length2);

Member Avatar for iamthwee

The only thing I can think of that is causing the problem must be the reading from the file part. (Basically what Deepz was saying)

Are you sure the end of the file has no extra spaces or newlines present?


Open your text file and keep pressing backspace so that the flashing cursor is right next to the last number in your file. Click save then try running the program again.

Why don't you post your entire code and your text file so we can see exactly what is going wrong.

And this is how I would read my file in:

/*
   * ped.java
   *
   * Created on 29 April 2006, 17:07
   */
import java.awt.*;
import java.io.*;
import java.util.*;


class Pedantic
{

   public static void main (String [] args)
   {

       try {
	      BufferedReader in = new BufferedReader(new FileReader("Myfile.txt"));
	      String str;
	      while ((str = in.readLine()) != null)//read in a line
	      {
	       
	       int length = str.length();
	       String c = str.substring(length-4,length);
	       int num = Integer.parseInt(c);
               //System.out.println(str);
	       System.out.println(num*2); //multiply last four digit by 2
	      }
	     in.close();
        }
      catch (IOException e)
      {

      }
        
   }

}

ok i will give my full source code for this Class in order you can help me in my Problem..
iam looking to implement digital signature and this class is responsible for appending the message to the Signature and extracting it from the message in order to make the verification process..
So i have the origional message stored in a text file,and also have the signature stored into another text file ...first of all i append these two files and it was appended but the problem was is that there was a line separator between the message and the Signature as following:

==============================================
Hello Bob, how are you? I am going to go to the movie tonight. I plan to see Gonewith the Wind. I really like Clark Gable. Would you like to go with me? I would really like tohave some company. Your friend
, Alice

511335051558680626415690127797000351618224974432826780852791138100851742238493708680633911102408
==============================================

i tried to solve my problem but i couldnt so i go on...i then store this in a new text file ...then i calculated the length of my origional message and represented it into four characters and then i appended it to the previous file and the result was as following:
================================================================================
Hello Bob, how are you? I am going to go to the movie tonight. I plan to see Gonewith the Wind. I really like Clark Gable. Would you like to go with me? I would really like tohave some company. Your friend
, Alice

5113350515586806264156901277970003516182249744328267808527911381008517422384937086806339111024080220
================================================================================


note 0220 was my message length ,afetr that i store this result in a new file and tried to extract the last four characters to know the length of the origional message and here was the problem we talked about (in using substring and ParseInt ....i hope yiu understood my application and now here is the full source code:

package final_append;
import java.io.*;
public class CopyBytes {
static String bobSignedMsg;
static  String SUBString;
static int bobMsgLen;
static String My_Message_Length  ;
static int len;
static String recv_Message;
static String Message_Length;
static int length2;
static String c;
static int num;
public static void main(String[] args) throws IOException {
/*==========================Printing the input message========================*/
try{
FileInputStream Message_File=new FileInputStream ("C:/JBuilder4/lib/output8.txt");
BufferedReader buff=new BufferedReader(new InputStreamReader(Message_File));
String Input_Message=new String();
System.out.println("Your input message is as following:");
while((Input_Message=buff.readLine() )!=null){
// Calculating the the length of our message in unit of bits
System.out.println(Input_Message);
len += Input_Message.length();
 
}
System.out.println(len);
/*==================here we will represent message length into four characters========================================================*/
  String My_Message_Length = "" + len;
    //Confirm number of characters in the string.
    if((My_Message_Length.length() > 4)
            || (My_Message_Length.length() <= 0)){
      System.out.println("Message length error.");
      System.exit(0);
    }//end if
    //Prepend leading zeros if necessary
    if(My_Message_Length.length() == 1){
                         My_Message_Length = "000"
                              + My_Message_Length;
    }else if(My_Message_Length.length() == 2){
      My_Message_Length = "00" + My_Message_Length;
    }else if(My_Message_Length.length() == 3){
      My_Message_Length = "0" + My_Message_Length;
    }else if(My_Message_Length.length() == 1){
                        My_Message_Length = "000"
                             + My_Message_Length;
    }
    System.out.println(My_Message_Length);
 
    /*=========================Append the message length string to the=========
    ========================= previously signed message=======================*/
// create writer for file to append to
BufferedWriter out = new BufferedWriter(
new FileWriter("C:/JBuilder4/lib/output6.txt", true));
// create reader for file to append from
BufferedReader in = new BufferedReader(new FileReader("C:/JBuilder4/lib/output4.txt"));
String str;
while ((str = in.readLine()) != null) {
out.write(str);
}
in.close();
out.close();
/*=================appending the length of message to My message=====================================================*/
BufferedWriter bw = null;
 bw = new BufferedWriter(new FileWriter("C:/JBuilder4/lib/output6.txt", true));
 bw.write(My_Message_Length);
 bw.newLine();
 bw.flush();
 
//======================Sending the Message to the Receiver Side================
recv_Message = null;
FileInputStream Received_Message=new FileInputStream ("C:/JBuilder4/lib/output6.txt");
BufferedReader buff2=new BufferedReader(new InputStreamReader(Received_Message));
System.out.println("Your Received message is as following:");
String four_characters = null;
int Four_characters_Integers;
while((recv_Message=buff2.readLine() )!=null){
// Calculating the the length of our message in unit of bits
System.out.println(recv_Message);
four_characters = recv_Message.substring(recv_Message.length() - 4);
Four_characters_Integers = Integer.parseInt(four_characters);
System.out.println("last four characters are:" + four_characters);
//length2 += recv_Message.length();
//SUBString = recv_Message.substring(recv_Message.length() - 4);
}
} catch (FileNotFoundException e) {
System.out.println("Cannot find file MyFile.txt \n" + e);
} catch (IOException e) {
System.out.println("IOException " + e);
} catch (NumberFormatException e) {
System.out.println("Not a number on the last 4 characters : " + recv_Message + "\n" + e);

in this stage it gave me the exception Not a number on the last 4 characters so why this happens????

Any Help Plzzzzzz.........

Have you tried any of the suggestions given yet?

Any Help Plzzzzzz.........

You seem to have dozed off :rolleyes:

Hi, back again (had a overheating CPU here, cooled down now 8-)

Do you still have a problem with the last code you posted.

I tried your code as below :

import java.io.*;
public class CopyBytes {
static String bobSignedMsg;
static  String SUBString;
static int bobMsgLen;
static String My_Message_Length  ;
static int len;
static String recv_Message;
static String Message_Length;
static int length2;
static String c;
static int num;
public static void main(String[] args) throws IOException {
/*==========================Printing the input message========================*/
try{
FileInputStream Message_File=new FileInputStream ("output8.txt");
BufferedReader buff=new BufferedReader(new InputStreamReader(Message_File));
String Input_Message=new String();
System.out.println("Your input message is as following:");
while((Input_Message=buff.readLine() )!=null){
// Calculating the the length of our message in unit of bits
System.out.println("MSG: " + Input_Message);
len += Input_Message.length();
 
}
System.out.println("LEN: " + len);
/*==================here we will represent message length into four characters========================================================*/
  String My_Message_Length = "" + len;
    //Confirm number of characters in the string.
    if((My_Message_Length.length() > 4)
            || (My_Message_Length.length() <= 0)){
      System.out.println("Message length error.");
      System.exit(0);
    }//end if
    //Prepend leading zeros if necessary
    if(My_Message_Length.length() == 1){
                         My_Message_Length = "000"
                              + My_Message_Length;
    }else if(My_Message_Length.length() == 2){
      My_Message_Length = "00" + My_Message_Length;
    }else if(My_Message_Length.length() == 3){
      My_Message_Length = "0" + My_Message_Length;
    }else if(My_Message_Length.length() == 1){
                        My_Message_Length = "000"
                             + My_Message_Length;
    }
    System.out.println(My_Message_Length);
 
    /*=========================Append the message length string to the=========
    ========================= previously signed message=======================*/
// create writer for file to append to
BufferedWriter out = new BufferedWriter(
new FileWriter("output6.txt", true));
// create reader for file to append from
BufferedReader in = new BufferedReader(new FileReader("output4.txt"));
String str;
while ((str = in.readLine()) != null) {
out.write(str);
}
in.close();
out.close();
/*=================appending the length of message to My message=====================================================*/
BufferedWriter bw = null;
 bw = new BufferedWriter(new FileWriter("output6.txt", true));
 bw.write(My_Message_Length);
 bw.newLine();
 bw.flush();
 
//======================Sending the Message to the Receiver Side================
recv_Message = null;
FileInputStream Received_Message=new FileInputStream ("output6.txt");
BufferedReader buff2=new BufferedReader(new InputStreamReader(Received_Message));
System.out.println("Your Received message is as following:");
String four_characters = null;
int Four_characters_Integers;
while((recv_Message=buff2.readLine() )!=null){
// Calculating the the length of our message in unit of bits
System.out.println(recv_Message);
four_characters = recv_Message.substring(recv_Message.length() - 4);
Four_characters_Integers = Integer.parseInt(four_characters);
System.out.println("last four characters are:" + four_characters);
//length2 += recv_Message.length();
//SUBString = recv_Message.substring(recv_Message.length() - 4);
}
} catch (FileNotFoundException e) {
System.out.println("Cannot find file MyFile.txt \n" + e);
} catch (IOException e) {
System.out.println("IOException " + e);
} catch (NumberFormatException e) {
System.out.println("Not a number on the last 4 characters : " + recv_Message + "\n" + e);
}
}
}

With the message as :

output8.txt : 'Hello Bob, how are you? I am going to go to the movie tonight. I plan to see Gonewith the Wind. I really like Clark Gable. Would you like to go with me? I would really like tohave some company. Your friend
, Alice
'
(without the ' offcourse)

end the sig output4.txt as : '511335051558680626415690127797000351618224974432826780852791138100851742238493708680633911102408
'

and i do not get an error. I get the following output :
'
Your input message is as following:
MSG: Hello Bob, how are you? I am going to go to the movie tonight. I plan to see Gonewith the Wind. I really like Clark Gable. Woul
d you like to go with me? I would really like tohave some company. Your friend
MSG: , Alice
LEN: 212
0212
Your Received message is as following:
5113350515586806264156901277970003516182249744328267808527911381008517422384937086806339111024080212
last four characters are:0212
5113350515586806264156901277970003516182249744328267808527911381008517422384937086806339111024080212
last four characters are:0212
'

Maybe you need to have a look with a hex editor what the last characters are as it seems to work OK.

If you still have the problem, move the line
System.out.println("last four characters are:" + four_characters);
up one line so it's before the cause of the exception to see what the string is.

Good Fortune,
Guido

Hi I could get the right result for using the Substring and getting the last four characters but no body gave me the solution for appending my two text files ,i dont need the two strings in the two text files to be separated by a line plz read the previous code for the appending operation and tell me where is the wrong here???


Hi, back again (had a overheating CPU here, cooled down now 8-)

Do you still have a problem with the last code you posted.

I tried your code as below :

import java.io.*;
public class CopyBytes {
static String bobSignedMsg;
static  String SUBString;
static int bobMsgLen;
static String My_Message_Length  ;
static int len;
static String recv_Message;
static String Message_Length;
static int length2;
static String c;
static int num;
public static void main(String[] args) throws IOException {
/*==========================Printing the input message========================*/
try{
FileInputStream Message_File=new FileInputStream ("output8.txt");
BufferedReader buff=new BufferedReader(new InputStreamReader(Message_File));
String Input_Message=new String();
System.out.println("Your input message is as following:");
while((Input_Message=buff.readLine() )!=null){
// Calculating the the length of our message in unit of bits
System.out.println("MSG: " + Input_Message);
len += Input_Message.length();
 
}
System.out.println("LEN: " + len);
/*==================here we will represent message length into four characters========================================================*/
  String My_Message_Length = "" + len;
    //Confirm number of characters in the string.
    if((My_Message_Length.length() > 4)
            || (My_Message_Length.length() <= 0)){
      System.out.println("Message length error.");
      System.exit(0);
    }//end if
    //Prepend leading zeros if necessary
    if(My_Message_Length.length() == 1){
                         My_Message_Length = "000"
                              + My_Message_Length;
    }else if(My_Message_Length.length() == 2){
      My_Message_Length = "00" + My_Message_Length;
    }else if(My_Message_Length.length() == 3){
      My_Message_Length = "0" + My_Message_Length;
    }else if(My_Message_Length.length() == 1){
                        My_Message_Length = "000"
                             + My_Message_Length;
    }
    System.out.println(My_Message_Length);
 
    /*=========================Append the message length string to the=========
    ========================= previously signed message=======================*/
// create writer for file to append to
BufferedWriter out = new BufferedWriter(
new FileWriter("output6.txt", true));
// create reader for file to append from
BufferedReader in = new BufferedReader(new FileReader("output4.txt"));
String str;
while ((str = in.readLine()) != null) {
out.write(str);
}
in.close();
out.close();
/*=================appending the length of message to My message=====================================================*/
BufferedWriter bw = null;
 bw = new BufferedWriter(new FileWriter("output6.txt", true));
 bw.write(My_Message_Length);
 bw.newLine();
 bw.flush();
 
//======================Sending the Message to the Receiver Side================
recv_Message = null;
FileInputStream Received_Message=new FileInputStream ("output6.txt");
BufferedReader buff2=new BufferedReader(new InputStreamReader(Received_Message));
System.out.println("Your Received message is as following:");
String four_characters = null;
int Four_characters_Integers;
while((recv_Message=buff2.readLine() )!=null){
// Calculating the the length of our message in unit of bits
System.out.println(recv_Message);
four_characters = recv_Message.substring(recv_Message.length() - 4);
Four_characters_Integers = Integer.parseInt(four_characters);
System.out.println("last four characters are:" + four_characters);
//length2 += recv_Message.length();
//SUBString = recv_Message.substring(recv_Message.length() - 4);
}
} catch (FileNotFoundException e) {
System.out.println("Cannot find file MyFile.txt \n" + e);
} catch (IOException e) {
System.out.println("IOException " + e);
} catch (NumberFormatException e) {
System.out.println("Not a number on the last 4 characters : " + recv_Message + "\n" + e);
}
}
}

With the message as :

output8.txt : 'Hello Bob, how are you? I am going to go to the movie tonight. I plan to see Gonewith the Wind. I really like Clark Gable. Would you like to go with me? I would really like tohave some company. Your friend
, Alice
'
(without the ' offcourse)

end the sig output4.txt as : '511335051558680626415690127797000351618224974432826780852791138100851742238493708680633911102408
'

and i do not get an error. I get the following output :
'
Your input message is as following:
MSG: Hello Bob, how are you? I am going to go to the movie tonight. I plan to see Gonewith the Wind. I really like Clark Gable. Woul
d you like to go with me? I would really like tohave some company. Your friend
MSG: , Alice
LEN: 212
0212
Your Received message is as following:
5113350515586806264156901277970003516182249744328267808527911381008517422384937086806339111024080212
last four characters are:0212
5113350515586806264156901277970003516182249744328267808527911381008517422384937086806339111024080212
last four characters are:0212
'

Maybe you need to have a look with a hex editor what the last characters are as it seems to work OK.

If you still have the problem, move the line
System.out.println("last four characters are:" + four_characters);
up one line so it's before the cause of the exception to see what the string is.

Good Fortune,
Guido

Member Avatar for iamthwee

If the line separater in the file is causing all the problems, can't you just ignore that line when you are reading it in?

there is no separator in any text file but when i append them together i get a line separator betwen them and i dont need this plz any help???u can see my code up and tell me wut to do??

there is no separator in any text file but when i append them together i get a line separator betwen them and i dont need this plz any help???u can see my code up and tell me wut to do??

You must be adding a newline somewhere in the code.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.