BinaryIO outputting SOH and STX instead of Int - java

I'm currently writing a program that will create a file and output as an integer how many times the code has been executed. this is my code:
import java.io.*;
public class Q1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int count;
File file = new File("count.dat");
try {
FileOutputStream os = new FileOutputStream(file,true);
FileInputStream is = new FileInputStream(file);
if (is.available() == 0)
count = 0;
else
count = is.read();
count++;
//System.out.println(count);
os.write(count);
os.close();
is.close();
} catch (FileNotFoundException e) {
System.out.println("file not found");
System.exit(0);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("IOException");
System.exit(0);
}
}
}
I've ran into a problem with the output, when I un-comment the sysout of count it has the correct number but when I run the program and view it with notepad++ it shows soh then for the second time it outputs the soh and stx. I don't understand where these outputs are coming, any help is appreciated.Thanks in advanced.

I've figured out that the output error was a problem with notepad but my file is getting overridden when I run the program.

Related

How to put read and cast into a char array

I have a source txt file and I am trying to read the characters using the .read() method of the FileReader class. I have got the integer values that come out the .read and cast them to char and looped the output to check this is working. The problem is that when I try to store them in an array, the array prints empty.
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class ReversedQuotation {
public static void main(String[] args) {
char[] charArray = new char[1000];
char[] sortedQuote = new char[1000];
int counter = 999;
int secondCounter = 0;
FileReader fr = null;
try {
fr = new FileReader("/Users/cal/Desktop/backwards.txt");
while(true) {
try {
int charInt = fr.read();
if(charInt == -1) break;
charArray[counter] = (char)charInt;
counter--;
System.out.print(charArray[counter]);
System.out.print((char)charInt); // just to check the characters are correct.
charArray[counter] = sortedQuote[secondCounter];
secondCounter++;
System.out.print(sortedQuote[secondCounter]);
}
catch (IOException e) {
System.out.println("IO Error in reading document");
e.printStackTrace();
}
}
} catch (FileNotFoundException e) {
System.out.println("Error finding document.");
} finally {
try {
fr.close();
} catch(IOException e) {
System.out.println("Error in closing the File Reader.");
}
}
}
}
First:
charArray[counter] = (char)charInt; // say counter = 999
counter--;
System.out.print(charArray[counter]); // charArray[998]
This will print the value at decremented index(which is essentially empty) and not the assigned index.
charArray[counter] = (char)charInt;
System.out.print(charArray[counter]);
counter--;
This should print what you have assigned.
Second:
sortedQuote[secondCounter] is never assigned and
charArray[counter] = sortedQuote[secondCounter] assignment seems to have no purpose.

Calling the main for another try after throwing an exception

I want to restart the program after throwing an exception this my code
System.out.println("please enter an intger to compute its factorial:");
BufferedReader bufferedreader = new BufferedReader( new InputStreamReader(System.in));
String number ="";
try {
try {
number = bufferedreader.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
intN=Integer.parseInt(number);
if (intN > 0) { // from the command line
FactorialIter f =
new FactorialIter(Math.abs(intN));
}
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
System.out.println("error you should enter a number");
throw new MyExceptions("try again please use integer numbers");
//if possible to restart the main
}
so when ever the user enters a character the program will throws an exception and then restarts is this possible??
In general, one should not be invoking main recursively, especially for the purpose of restarting the program.
If you want to go back to a certain point in your program, use a loop. Here is one example of how you can do it:
boolean done = false;
do {
done = true;
try {
...
} catch (NumberFormatException e) {
System.out.println("error you should enter a number");
done = false;
}
} while (!done);
The loop will continue from the beginning each time the exception handler sets done to false.
You could just put it in a loop.
While(isValid != TRUE)
{
try
{
try {
number = bufferedreader.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
intN=Integer.parseInt(number);
if (intN > 0) { // from the command line
FactorialIter f =
new FactorialIter(Math.abs(intN));
isValid = TRUE;
}
}
catch (NumberFormatException e)
{
System.out.println("error you should enter a number");
System.out.println("try again please use integer numbers");
isValid = FALSE;
}
}

Multiple Audio files won't concatenate

I'm trying to create a simple recorder which gives 'pause' and 'resume' functionality to the user.
Since Android does not support this directly, I'm creating individual files whenever the user presses 'Pause' and 'Resume' with the suffixes _1, _2, so on.
I use the code below to concatenate them
public void mergeAllAndSave() {
// TODO Auto-generated method stub
Enumeration<FileInputStream> allRecordings;
Vector<FileInputStream> audiofiles = new Vector<FileInputStream>();
for (int i = 1; i < count+1; i++) {
try {
audiofiles.add(new FileInputStream(Environment.getExternalStorageDirectory().getPath() + "/"+ AUDIO_RECORDER_FOLDER + "/" + _filename + "_"+ i + file_exts[currentFormat]));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
allRecordings = audiofiles.elements();
SequenceInputStream siStream = new SequenceInputStream(allRecordings);
try {
FileOutputStream foStream = new FileOutputStream(Environment.getExternalStorageDirectory().getPath() + "/"+ AUDIO_RECORDER_FOLDER + "/" + _filename + file_exts[currentFormat]);
int temp;
while ((temp = siStream.read() ) != -1) {
foStream.write(temp);
}
foStream.close();
siStream.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
The code works fine. It gives me a single file. However it contains the contents of the first file only. Logcat does not show any errors, whatsoever.
Anyone with any ideas what is the mistake I am making?
Thanks.
Answer to this question is here.
PS: I cannot add this as a comment because I do not have sufficient reputation.

Output to file from arraylist not working - java

I'm trying to create a program that outputs a bunch of integers from an arraylist to a file, however all I get is a bunch of question marks in the .dat file. Can anyone see what my problem is?
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter("energy.dat"));
for(int x = 0; x< energy.size(); x++){
writer.write(energy.get(x));
}
} catch (IOException e) {
System.err.println(e);
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
System.err.println(e);
}
}
}
Assuming energy is List<Integer> you're calling BufferedWriter.write(int). This method is not writing a text representation of the number. To write 1 you'd have to call write like this: writer.write((int)'1'). This is not the same as writer.write(1).
Replace
writer.write(energy.get(x));
with
String s = String.valueOf(energy.get(x));
writer.write(s, 0, s.length();

Issue with reading data from a socket and appending it to a stringbuilder

I have followed some tutorials to create a basic server that can handle multiple clients at once. It receives data correctly but it chews up more and more memory until it runs out of heap space. I believe it is because my loop is not recognising my end character and leaving the for loop.
Here is the code for the thread which receives the data:
while (true){
try {
is = new BufferedInputStream(s.getInputStream());
InputStreamReader isr = new InputStreamReader(is);
int character;
StringBuilder process = new StringBuilder();
try {
while((character = isr.read()) != 13) {
process.append((char)character); //here is the issue - it just continues to append until it runs out of memory
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
parent.parent.writeToLog("Client " + Integer.toString(num) + " sent a message: " + process.toString());
System.out.println(process);
is = null;
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
BufferedOutputStream os;
try {
os = new BufferedOutputStream(s.getOutputStream());
OutputStreamWriter osw = new OutputStreamWriter(os);
osw.write("Response from server at client socket " + Integer.toString(num) + " at " + (new java.util.Date()).toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I've put a comment into the code where it shows me the error on the stack trace. Here is the client, which is just the EchoClient from the Java tutorials:
import java.io.*;
import java.net.*;
import java.util.Random;
public class EchoClient {
public static void main(String[] args) throws IOException {
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
echoSocket = new Socket("localhost", 2405);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: taranis.");
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for "
+ "the connection to: taranis.");
System.exit(1);
}
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
out.println("Message to host: hello" + (char) 13);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
out.println(Integer.toString((new Random()).nextInt()) + (char) 13);
out.close();
in.close();
stdIn.close();
echoSocket.close();
}
}
You can see where I append the character 13 to the output and that is what is meant to end the loop but from my understanding this is not working. Could anyone help me out with this?
I think the problem lies in the following code:
while((character = isr.read()) != 13) {
process.append((char)character); //here is the issue - it just continues to append until it runs out of memory
}
Even when end of stream is reached isr.read() would return -1 and not 13. There's a possibility that you are never receiving input character that is 13 to exit out of the loop.
This is likely the problem: while((character = isr.read()) != 13)
Why are you checking for 13? InputStreamReader.read() will return -1 if the end of the stream is reached.
My guess is that you're hitting the end of the stream and filling your StringBuilder with garbage. Note that (char)-1 actually represents the unicode character 65535.

Categories