Getting output of System.out as file - file

I'm new to programming and working on this project of Library System.
It uses linked lists to save details of books and members.
It has two functions that print details of all books in library and all members of library.
As I made a GUI for my project I can't print details in Frame.
So, I thought of doing it with file.
I have successfully printed everything in file but now my problem is how should I display file to user?
Like if user presses "show all books" button, it should automatically open the respective file.
I tried searching but I can't figure out what to actually search as I'm a beginner.
Any help would be much appreciated please.
UPDATE:
I tried with Desktop.getDesktop(file) and I am getting this error.
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "Book issued successfully"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Long.parseLong(Long.java:589)
at java.lang.Long.parseLong(Long.java:631)
at RunProgram.stringToLong(RunProgram.java:217)
at RunProgram.actionPerformed(RunProgram.java:196)
This is my stringToLong method
private static long stringToLong(String stringObject){
return Long.parseLong(stringObject.trim());
}
This is the method for printing details
void printBooksIssued(long cpr) throws IOException{
File file = new File("d:/work/test.txt");
System.setOut(new PrintStream(new FileOutputStream(file)));
int index = 0;
if (searchMember(cpr) == -1)
System.out.println("Member doesn't exist.");
LibMember m = membersList.get(index);
while (index < sizeMembersList() ){
if (m.getCprNum() == cpr){
System.out.println(Arrays.toString(m.getBooksIssued()));
return;
}
index++;
if (index < sizeMembersList())
m = membersList.get(index);
}
Desktop.getDesktop().open(file);
}
And this is how I called this method inside actionListener method.
case "Print details of books issued to member": {
long cprNum = stringToLong(cpr.getText());
try {
ITLib.printBooksIssued(cprNum);
}
catch (IOException e1){
fName.setText("Error. Make sure CPR number is correct and try again.");
}
}
The thing I don't understand is that the first error of numberFormatException of string "Book issued successfully is completely separate from this button and textfield. Then why is it giving error with that.
case "Issue": {
long an = stringToLong(NUM.getText());
long cpr = stringToLong(CPR.getText());
if (ITLib.issueBook(an, cpr))
NUM.setText("Book issued successfully");
else
NUM.setText("Book couldn't be issued. Try again later.");
break;
}

If you are using Java and save the files with the suffix ".txt", you can use Desktop.getDesktop().
Here is an example that will popup the default system editor for text:
File file = new File("d:/work/test.txt");
System.setOut(new PrintStream(new FileOutputStream(file)));
System.out.println("Testing 1");
System.out.println("Testing 2");
Desktop.getDesktop().open(file);
On Windows this will open notepad.exe with the "text.txt" file.

Related

Send and receive a w3c.dom.Document over socket as byte[] Java

I send a document over socket like this:
sendFXML(asByteArray(getRequiredScene(fetchSceneRequest())));
private void sendFXML(byte[] requiredFXML) throws IOException, TransformerException {
dataOutputStream.write(requiredFXML);
dataOutputStream.flush();
}
private Document getRequiredScene(String requiredFile) throws IOException, ParserConfigurationException, SAXException, TransformerException {
return new XMLLocator().getDocumentOrReturnNull(requiredFile);
}
private String fetchSceneRequest() throws IOException, ClassNotFoundException {
return dataInputStream.readUTF();
}
On the side of XMLLocator it finds the correct document and parses it right. I see it by printing the whole doc in console.
But I cannot handle it on the clients side where it's fetch by:
public static void receivePage() throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] data = new byte[989898];
int bytesRead = -1;
while((bytesRead = dataInputStream.read(data)) != -1 ) { //stops here
baos.write(data, 0, bytesRead );
}
Files.write(Paths.get(FILE_TO_RECEIVED), data);
}
After the first iteration in while() cycle it just stops on the commented place.
I don't know if I have an error on the side of the server and I send this in doc in an incorrect format or I read the sent byte array incorrectly. Where is the problem?
Edit:
For the debug purpose, in the receivePage() method, I've chosen a different way of reading the byte array from server which goes like:
int count = inputStream.available();
byte[] b = new byte[count];
int bytes = dataInputStream.read(b);
System.out.println(bytes);
for (byte by : b) {
System.out.print((char)by);
}
And now I'm able to print fetched FXLM in console but a new problem has appeared.
On debug, it normally receives the byte[] from server, writes 2024 for count and displayes the content of the file but if I run the app normally via Shift + f10 it fetches nothing and just writes 0 in console
Edit2:
For some reason, once again, on debug, it's able to even write into a file
for (byte by : b) {
Files.write(Paths.get(FILE_TO_RECEIVED), b);
System.out.print((char)by);
}
But when I try to return this fxml on debug and then show like this:
Parent fxmlToShow = FXMLLoader.load(getClass().getResource("/network/gui.fxml"));
Scene childScene = new Scene(fxmlToShow);
Stage window = (Stage)((Node)ae.getSource()).getScene().getWindow();
window.setScene(childScene);
return window;
It shows only previous files. Like on the first attempt of debug it show a blank page when I asked for the 1st one from server. On the second attempt of debug when i ask for 3rd page from server, it shows me the previously asked one and so on.
To me, it seems absolutely insane cuz the fxml rile actually refreshes before the line
Parent fxmlToShow = FXMLLoader.load(getClass().getResource("/network/gui.fxml"));
is invoked.
Yeah, thank everybody for participating.
So, the issue of incorrect displaying if FXML files was caused by the incorrect FILE_TO_RECEIVED path.
When FXMLLoader.load(getClass().getResource("/network/gui.fxml")); loads gui.fxml it takes it not from D:\\JetBrains\\IdeaProjects\\Client\\src\\network\\gui.fxml,im my case, but from D:\\JetBrains\\IdeaProjects\\Client\\OUT\\PRODUCTION\\Client\\network\\gui.fxml.
As for me, that doesn't seem obvious.
What about different behaviour on debug and on run. In method receivePage() it needs to wait until connection is available.
int count = inputStream.available();
If you read docs for this method you will see
Returns an estimate of the number of bytes that can be read (or skipped over) from this input stream ...
The available method for class InputStream always returns 0...
So, you jext need to wait for connection to be available
while(inputStream.available()==0){
Thread.sleep(100);
}
Otherwise it just prepares byte[] b = new byte[count]; for 0 bytes and you can write in nothing.

Lost on how to implement writeCharecteristic in my android code

I am using android studio's example bluetoothlegatt, which has a read function and and works completely find (it interacts with the TI keyfob I have which sends over values when pressed).
However, I have no idea how to put in writeCharecteristic because my previous attempts have failed.
Can someone help me with this? I would like to send a "1" over so that the keyfob's led lights up.
Edit: I have tried something like this
public void writeCharacteristic(byte[] value) { BluetoothGattService LumService = mBluetoothGatt.getService(UUID_LUM_APP);
if (LumService == null) {
System.out.println("LumService null"); return; }
BluetoothGattCharacteristic LumChar = LumService.getCharacteristic(UUID_LUM_CHAR);
if (LumChar == null) {
System.out.println("LumChar null"); return; }
LumChar.setValue(value); boolean status = mBluetoothGatt.writeCharacteristic(LumChar);
System.out.println("Write Status: " + status);
This is not my code, though, just an example. I want to integrate this into the bluetoothlegatt given already, but I have had no success with it.

Getting path of audio file from sdcard

In my app I tried to pass the file path from one activity to another activity using intent.In my receiving activity I got the file path as "null".But when I print the file in first activity it prints the path.From my second activity I attach that file to mail using Gmailsender.This was the code I tried,
private void startRecord()
{
File file = new File(Environment.getExternalStorageDirectory(), "test.pcm");
try
{
file.createNewFile();
OutputStream outputStream = new FileOutputStream(file);
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream);
DataOutputStream dataOutputStream = new DataOutputStream(bufferedOutputStream);
int minBufferSize = AudioRecord.getMinBufferSize(8000,
AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT);
short[] audioData = new short[minBufferSize];
AudioRecord audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC,
8000,
AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT,
minBufferSize);
audioRecord.startRecording();
while(recording)
{
int numberOfShort = audioRecord.read(audioData, 0, minBufferSize);
for(int i = 0; i < numberOfShort; i++)
{
dataOutputStream.writeShort(audioData[i]);
}
}
audioRecord.stop();
audioRecord.release();
dataOutputStream.close();
}
catch (IOException e)
{
e.printStackTrace();
}
String audiofile;
audiofile=file.getAbsolutePath();
System.out.println("File Path::::"+audiofile);
}
Intent is,
Intent sigout=new Intent(getApplicationContext(),WeeklyendActivity.class);
sigout.putExtra("mnt/sdcard-test.pcm",audiofile);
startActivity(sigout);
In my receiving activity,
String patty=getIntent().getStringExtra("mnt/sdcard-text.pcm");
System.out.println("paathhhy frfom ::"+patty);
It prints null.Can anyone help me how to get the file path.And more thing I am not sure whether the audio would save in that file correctly?
Please anyone help me!!!Thanks in advance!
Based on your information that audioFile is a variable of type File, when you do this:
sigout.putExtra("mnt/sdcard-test.pcm",audiofile);
you are putting a File object in the extras Bundle. Then, when you try to get the extra from the Bundle you do this:
String patty=getIntent().getStringExtra("mnt/sdcard-text.pcm");
However, the object in this extra is of type File, not type String. This is why you are getting null.
If you only want to pass the name of the file, then put the extra like this:
sigout.putExtra("mnt/sdcard-test.pcm",audiofile.getAbsolutePath());

get email attatchment for POP 3 received as winmail.dat

When I try to get attatchment from POP 3 mail, I am getting them as winmail.dat, not the original attached file name. How can I get the original file name?
for (int i = 0; i < multipart.getCount(); i++)
{
BodyPart bodyPart = multipart.getBodyPart(i);
if(!Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition()))
{
//do something
}
else
{
bodyPart.getFileName(); // here only get the winmail.dat
}
}
This is part of the Exchange Settings, and sadly you going to need to extract the original contents from the WinMail.dat using JTNEF.
"The Java TNEF package is an open source code implementation of a TNEF message handler, which can be used as a command-line utility or integrated into Java-based mail applications to extract the original message content."
This is found on the JavaMail's third party tools.
As alternative and what looks simpler is POI-HMEF
Sample extraction:
public void extract(String winmailFilename, String directoryName) throws Exception {
HMEFContentsExtractor ext = new HMEFContentsExtractor(new File(winmailFilename));
File dir = new File(directoryName);
File rtf = new File(dir, "message.rtf");
if(! dir.exists()) {
throw new FileNotFoundException("Output directory " + dir.getName() + " not found");
}
System.out.println("Extracting...");
ext.extractMessageBody(rtf);
ext.extractAttachments(dir);
System.out.println("Extraction completed");
}
There is also a sample for printing the contents here.

Database problem: how to diagnose and fix the problem?

I created an application which stores values into the database and retrieves the stored data. While running an application in run mode everything seems to work fine (the values are stored and retrieved successfully) but when I run in the debug mode the process throws IllegalStateException and so far haven't found a cause.
The method which retrieves an object Recording is the following:
public Recording getRecording(String filename) {
Recording recording = null;
String where = RECORDING_FILENAME + "='" + filename + "'";
Log.v(TAG, "retrieving recording: filename = " + filename);
try {
cursor = db.query(DATABASE_TABLE_RECORDINGS, new String[]{RECORDING_FILENAME, RECORDING_TITLE, RECORDING_TAGS, RECORDING_PRIVACY_LEVEL, RECORDING_LOCATION, RECORDING_GEO_TAGS, RECORDING_GEO_TAGGING_ENABLED, RECORDING_TIME_SECONDS, RECORDING_SELECTED_COMMUNITY}, where, null, null, null, null);
if (cursor.getCount() > 0) {
cursor.moveToFirst();
//String filename = c.getString(0);
String title = cursor.getString(1);
String tags = cursor.getString(2);
int privacyLevel = cursor.getInt(3);
String location = cursor.getString(4);
String geoTags = cursor.getString(5);
int iGeoTaggingEnabled = cursor.getInt(6);
String recordingTime = cursor.getString(7);
String communityID = cursor.getString(8);
cursor.close();
recording = new Recording(filename, title, tags, privacyLevel, location, geoTags, iGeoTaggingEnabled, recordingTime, communityID);
}
}
catch (SQLException e) {
String msg = e.getMessage();
Log.w(TAG, msg);
recording = null;
}
return recording;
}
and it is called from another class (Settings):
private Recording getRecording(String filename) {
dbAdapter = dbAdapter.open();
Recording recording = dbAdapter.getRecording(filename);
dbAdapter.close();
return recording;
}
While running through the code above everything works fine but then I notice an exception in another thread:
alt text http://img509.imageshack.us/img509/862/illegalstateexception.jpg
and don't know neither what is the possible cause of this exception nor how to debug the code from that thread to diagnose the cause.
I would be very thankful if anyone knew what is the possible issue here.
Thank you!
Looks like that cursor.close() is inside an "if" - that's when SQLiteCursor.finalize() will throw an IllegalStateException (I googled for it). You migh be getting an empty recordset, for instance, if some other process/thread didn't have the time to commit.
Close it always, even if it's result set is empty.
I'd also advice you to access fields by names, not indices, for future compatibility. And do both close()s in finally{} blocks.

Resources