The package java.util.logging is not accessible in Java - java

I am trying run simple hello word java program and want to log hellow world.
But I am getting error as
"The package java.util.logging is not accessible" on the statement
import java.util.logging.*; in eclipse.
I am using Java 11 version
Complete code below
package myproject;
import java.io.Console;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.logging.Logger;
import java.util.logging.*;
public class FileOperations {
public static void main(String[] args) {
// Create a Logger
Logger logger = Logger.getLogger(FileOperations.class.getName());
// Call info method
logger.info("This is message 1");
// TODO Auto-generated method stub
File file=new File("myFile.txt");
FileOutputStream fos;
try {
fos = new FileOutputStream(file);
fos.write(2);
System.out.println("File operation completed");
Logger.log(Level.INFO, "My first Log Message");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

If you have a module-info.java file, then add
requires java.logging;

Maybe the problem with creating a Logger object?
Logger logger = Logger.Leve
It seems that it is not completed.

Related

Is there a problem with BufferedWriter in JAVA?

I'm quite new in OOP and Java programming, so please, forgive me.
I wrote a small class in which I try to write a String in a file using the BufferedReader class.
Everything works just fine, but the file is "empty", I mean that I can't see anything inside.
But for sure, data are stored, because when I close Eclipse and re open it again and run the driver class to make my tests, data are restored from the file.
By the way I use a "try with resources" mechanism so my file is "closed" automatically.
Does someone already meet this problem?
My Eclipse version is "2018-12"
Below, you have the small class with a "writeToFile" method in which I use the BufferedReader class.
package parlons.code.tipcalulator.utilities;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class FileManagement {
private File tipFile;
public FileManagement(String tipsFileName) {
this.tipFile = new File("/"+tipsFileName);
}
public String readFromFile() {
String tip = null;
try(BufferedReader bufferedReader = new BufferedReader(new FileReader(this.tipFile))) {
tip = bufferedReader.readLine();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return tip;
}
public void writeToFile(String decimal) {
try(BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(tipFile,true))){
bufferedWriter.write(decimal);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Below, you'll find the Driver class for testing purposes.
package parlons.code.tipcalulator.utilities;
public class UtilitiesTestDriver {
public static void main(String[] args) {
String decimal = "108";
FileManagement fileManagement = new FileManagement("tipFile.txt");
fileManagement.writeToFile(decimal);
System.out.println(fileManagement.readFromFile());
}
}
As per Makoto's comment above, everything works fine if you change to e.g.:
this.tipFile = new File("./"+tipsFileName);
This would create the tipFile.txt file (containing 108) in the root directory of your project (as opposed to the root of the filesystem - where you would probably not have write permission.)

FileOutputStream doesn't show FileNotFoundException

for FileOutputStream, it will throw a FileNotFoundException if the file doesn't exist, but it will create it if it can.
I dont have a Sample.txt in my project root
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
public class Main {
public static void main(String[] args) {
try {
FileOutputStream s= new FileOutputStream("Sample.txt");
} catch (FileNotFoundException e) {
System.out.println("File not Found");
}
}
}
The problem is:
I cannot see the Output of the "File Not Found" from the Terminal. How did it happen?
Thank you
You can set Sample.txt as a File first and check if it exists with .canWrite()
You still have to put a try/catch around FileOutputStream, but it should never go in the catch block.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
public class test {
public static void main(String[] args) {
File f = new File("Sample.txt");
if (!f.exists()) {
System.out.println("File not Found");
}
else {
try {
FileOutputStream s = new FileOutputStream(f);
} catch (FileNotFoundException e) {}
}
}
}

How to save received messages in separate files with messagelistener

Disk.class implementation
package server;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;
import services.CustomerData;
public class Disk implements MessageListener{
private int index;
private FileWriter f;
private BufferedWriter b;
public Disk(int i){
this.index=i;
try {
f = new FileWriter("disk"+i+".txt",true);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
b = new BufferedWriter(f);
}
#Override
public void onMessage(Message m) {
try {
if(m instanceof ObjectMessage){
CustomerData c = (CustomerData) ((ObjectMessage) m).getObject();
b.write(c.getSurname()+" "+c.getName()+" "+c.getAge());
b.newLine();
b.flush();
System.out.println("disk"+index+".txt saved");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JMSException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
So, what happens is that every message received by every message listener is saved in the same file (the last indexed disk.txt file) but I want to save them in every single file, from 0 to N. N txt files are created but they are not modified except the last one.
EDIT: I added the FileWriter and BufferedWriter in the Disk contructor but it will create N files but modify the last one only.
Main class there Disk is created:
package server;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.rmi.RemoteException;
import java.util.Hashtable;
import javax.jms.JMSException;
import javax.jms.Session;
import javax.jms.Topic;
import javax.jms.TopicConnection;
import javax.jms.TopicConnectionFactory;
import javax.jms.TopicSession;
import javax.jms.TopicSubscriber;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
public class StorageServer {
public static final int N = 10;
public static void main(String[] args) throws RemoteException {
Hashtable<String,String> prop = new Hashtable<String,String>();
prop.put("java.naming.factory.initial", "org.apache.activemq.jndi.ActiveMQInitialContextFactory");
prop.put("java.naming.provider.url", "tcp://127.0.0.1:61616");
prop.put("topic.req", "requests");
System.setProperty("org.apache.activemq.SERIALIZABLE_PACKAGES","*");
try {
Context jndiCon = new InitialContext(prop);
TopicConnectionFactory tConnFact = (TopicConnectionFactory) jndiCon.lookup("TopicConnectionFactory");
TopicConnection tConn = tConnFact.createTopicConnection();
TopicSession tSess = tConn.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
Topic topic = (Topic) jndiCon.lookup("req");
TopicSubscriber subscriber = tSess.createSubscriber(topic);
tConn.start();
for(int i=0; i<N; i++){
//FileWriter file = new FileWriter("disk"+i+".txt",true);
subscriber.setMessageListener(new Disk(i));
System.out.println("New disk"+i+" started");
}
} catch (NamingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JMSException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
You have a single TopicSubscriber which has a single MessageListener (hence the setMessageListener and not addMessageListener). You need to create a separate TopicSubscriber for each listener with
for(int i=0; i<N; i++){
TopicSubscriber subscriber = tSess.createSubscriber(topic);
subscriber.setMessageListener(new Disk(i));
System.out.println("New disk"+i+" started");
}
I'd also recommend avoiding using the FileWriter (and FileReader) class, because it uses the platform encoding. This can cause surprises when platform (or its encoding) changes. The equivalent, but longer and safer way is:
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("whatever.txt"), "UTF-8"));
With UTF-8 being a safe encoding to use.

Cannot Start a Method In a Different Class Using a Library

I've just created my first library for an Android app I've built (I have code I need to reuse in the future across different apps) and I need to start a method I have in the main project from the library - however when I attempt to do so using the line:
com.project.sample.datasettings.UpdateActivity.success();
I'm getting a compiler error stating:
com.project.sample.UpdateActivity Cannot Be Resolved To A Type
SOURCE:
package com.project.sample.networktasklibrary;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.util.zip.GZIPInputStream;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLException;
import com.project.sample.networktasklibrary.XmlParserHandlerFinal;
import com.project.sample*;
import org.xml.sax.SAXException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
// this class performs the call to webservice in the background
public class NetworkTask extends AsyncTask<String, String, InputStream> {
private static final String LOG_TAG = "STDataSettings";
private static final String TAG_RESULT = "success";
private static InputStream stream;
#Override
protected InputStream doInBackground(String... params) {
try {
stream = getQueryResults("https://dl.dropboxusercontent.com/u/31771876/GetPhoneSettings-ST-rsp-eng.xml");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return stream;
}
/*
* Sends a query to server and gets back the parsed results in a bundle
* urlQueryString - URL for calling the webservice
*/
protected static synchronized InputStream getQueryResults(
String urlQueryString) throws IOException, SAXException,
SSLException, SocketTimeoutException, Exception {
Bundle queryResults = new Bundle();
HttpsURLConnection https = null;
String uri = urlQueryString;
URL urlo = new URL(uri);
https = (HttpsURLConnection) urlo.openConnection();
https.setConnectTimeout(50000); // 20 second timeout
https.setRequestProperty("Connection", "Keep-Alive");
try {
https = (HttpsURLConnection) urlo.openConnection();
if ("gzip".equals(https.getContentEncoding())) {
stream = new GZIPInputStream(stream);
} else
stream = https.getInputStream();
} catch (SSLException e) {
Log.e(LOG_TAG, e.toString());
e.printStackTrace();
} catch (SocketTimeoutException e) {
Log.e(LOG_TAG, e.toString());
e.printStackTrace();
} catch (IOException e) {
Log.e(LOG_TAG, e.toString());
e.printStackTrace();
} catch (Exception e) {
Log.e(LOG_TAG, e.toString());
e.printStackTrace();
} finally {
}
String queryResult = null;
queryResults.putString(TAG_RESULT, queryResult);
return stream;
}
public InputStream getInputStream() {
return stream;
}
protected void onPostExecute(InputStream queryResults) {
// TODO Auto-generated method stub
super.onPostExecute(queryResults);
com.project.sample.datasettings.UpdateActivity.success();
}
}
UPDATE ACTIVITY CODE SAMPLE:
public void success() {
// to parse the response
try {
handler.getQueryResponse(stream);
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// to set method to save the ArryaLists from the parser
setArrayList();
Intent i = new Intent(this, ConfigFinalActivity.class);
startActivity(i);
}
Have you ever tried to add the library to the main project?
Right click the Project name -> Property -> Android -> Add. Then choose the library project.

Java program terminating after ObjectMapper.writeValue(System.out, responseData) - Jackson Library

I'm using the Jackson library to create JSON objects, but when I use the mapper.writeValue(System.out, responseData) function, the program terminates. Here is my code:
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
public class Test {
public static void main(String[] args){
new Test().test();
}
public void test() {
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> responseData = new HashMap<String, Object>();
responseData.put("id", 1);
try {
mapper.writeValue(System.out, responseData);
System.out.println("done");
} catch (JsonGenerationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JsonMappingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}.
}
After this executes, the console shows {"id":1}, but does not show "done".
The problem is with the Jackson implementation, as ObjectMapper._configAndWriteValue calls UtfGenerator.close(), which calls PrintStream.close().
I'd log an issue at https://jira.codehaus.org/browse/JACKSON
To change the default behavior of target being closed you can do the following:
mapper.configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET, false);
While declaring variable names in your data files/getter files, the first letter should be small.

Categories

Resources