I have created a method writeFile which writes directly to a File if the flag is true. If the flag is false it reads the File, retrieves the Object, appends something and again saves it to the File. I am getting EOFException when the flag is true.
Here is the whole class I am experimenting with:
public class HandleObjects{
public final static String PATH = "/home/user/Desktop/exp.conf" ;
public static boolean i = true ;
public static void main(String[] args) throws JSONException, IOException, ClassNotFoundException {
JSONObject obj = new JSONObject();
obj.put("id", "something");
JSONObject obj1 = new JSONObject();
obj1.put("key", "xxxxxxxxxxxxxxx");
obj1.put("token", "xxxxxxxxxxxxx");
writeFile(obj,false);
readFile();
writeFile(obj1,true); // Exception occurs here
readFile();
}
public static void writeFile(JSONObject o, boolean flag ) throws FileNotFoundException, IOException, JSONException, ClassNotFoundException{
ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(PATH)) ;
JSONObject ob = null ;
if (flag){
ob = readfile();
ob.append("extra", o);
os.writeObject(ob.toString());
}
else{
os.writeObject(o.toString());
}
os.flush() ;
os.close();
}
public static JSONObject readFile() throws FileNotFoundException, IOException, JSONException, ClassNotFoundException{
ObjectInputStream is = new ObjectInputStream(new FileInputStream(PATH)) ;
String str= (String) is.readObject() ;
JSONObject o = new JSONObject(str);
is.close() ;
return o ;
}}`
You've already created a new empty file before you call readfile() when you're in 'append' mode, so of course you get EOF when trying to read an object. There aren't any. You need to call readfile() before creating the FileOutputStream.
Related
Can you tell me why I can't see my list when I try to start it from another method? Below methods:
public class CollectionsOperation {
private List<Client> bufferedReaderClientLIst = new ArrayList<Client>();
private List<Client> emptyBoxForCf = new ArrayList<Client>();
BufferedReader bf = null;
private static final String fileName = "Clients.txt";
public List<Client> bufferedReaderCollection() throws IOException {
String line;
bf = new BufferedReader(new InputStreamReader (new FileInputStream(fileName), "UTF-8"));
while((line = bf.readLine()) != null) {
String[] split = line.split(";");
String nameCompany = split[0].substring(2);
String adress = split[1];
String phoneNumber = split[2];
String emailAdress = split[3];
Client k = new Client(nameCompany, adress, phoneNumber, emailAdress);
bufferedReaderClientLIst.add(k);
}
System.out.println(bufferedReaderClientLIst);
return bufferedReaderClientLIst;
}
public void show() throws IOException {
CollectionsOperation k = new CollectionsOperation();
k.bufferedReaderCollection();
System.out.println(bufferedReaderClientLIst);
}
Calling the method:
public static void main(String[] args) throws IOException {
CollectionsOperation k = new CollectionsOperation();
k.show();
}
And this is the result what I get:
[ MarkCompany';Ilusiana';0982882902';mark#company.com, CorporationX';Berlin';93983';X#Corporation.com]
[]
Why the second list is empty ? the method bufferedReaderCollection() returns a result and the list bufferedReaderClientLIst is available to all methods. What is wrong?
In show():
public void show() throws IOException {
CollectionsOperation k = new CollectionsOperation();
k.bufferedReaderCollection();
System.out.println(bufferedReaderClientLIst);
}
You create another CollectionsOperation object to call bufferedReaderCollection() on. This is unnecessary.
However the problem is in the last print statement where you print bufferedReaderClientList. This is printing the bufferedReaderClientList of the this instance, not k. Because you have not called bufferedReaderCollection on this, the list will be empty, hence the [] printed at the end.
Instead of creating another instance, use this:
public void show() throws IOException {
this.bufferedReaderCollection();
System.out.println(bufferedReaderClientLIst);
}
I would like to use CognitiveJ (GitHub from CognitiveJ) but all I get is:
Status:401; Body: {"error":{"code":"Unspecified","message":"Access denied due to invalid subscription key. Make sure you are subscribed to an API you are trying to call and provide the right key."}}
Here is the Code:
public static String lic1 = "xxx";
public static String lic2 = "xxx";
public static void main(String[] args) throws IOException {
new Bildkontrolle();
}
public Bildkontrolle() throws IOException {
File imageFile = new File("E:\\DSC00306.jpg");
new FaceRecognicion(lic1, lic2, imageFile);
}
And here the second class:
public FaceRecognicion(String lic1, String lic2, File imageFile) throws IOException {
BufferedImage bufImage = ImageIO.read(imageFile);
InputStream inpStream = new FileInputStream(imageFile);
FaceScenarios faceScenarios = new FaceScenarios(lic1,
lic1);
ImageOverlayBuilder imageOverlayBuilder = ImageOverlayBuilder.builder(bufImage);
imageOverlayBuilder.outlineFacesOnImage(faceScenarios.findFaces(inpStream), RectangleType.FULL,
CognitiveJColourPalette.STRAWBERRY).launchViewer();
}
Does anyone have an examplecode where I can look up how to use the API.
I stuck at the point where to send the Request.
it's my first question here, i've try to be the more explicit :)
I want get value from a JSON page : https://api.dailymotion.com/video/x3p6d9r?fields=onair.
I have follow a tutorial about json object.
But i want get the value "onair" and put this in a String for use a IF STRING == "XX".
This is my code :
public class notification extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notification);
detectonline();
}
public void detectonline(){
/*
if (xx == "false") {
Do something is live is off
}
else{
Do something is live is on
}
*/
}
public static boolean checkIfOnline(String channel) throws IOException {
String channerUrl = "https://api.dailymotion.com/video/x3p6d9r?fields=onair";
String jsonText = readFromUrl(channerUrl);// reads text from URL
JsonParser parser = new JsonParser();
JsonObject json = parser.parse(jsonText).getAsJsonObject();
return !json.get("onair").isJsonNull();
}
private static String readFromUrl(String url) throws IOException {
URL page = new URL(url);
StringBuilder sb = new StringBuilder();
Scanner scanner = null;
try{
//scanner = new Scanner(page.openStream(), StandardCharsets.UTF_8.name());
scanner = new Scanner(page.openStream());
while (scanner.hasNextLine()){
sb.append(scanner.nextLine());
}
}finally{
if (scanner!=null)
scanner.close();
}
return sb.toString();
}
}
I remake your method according what you are looking for it's one of several way to parse json data :
public static boolean checkIfOnline(String channel) throws JSONException, IOException {
String channerUrl = "https://api.dailymotion.com/video/x3p6d9r?fields=onair";
String jsonText = readFromUrl(channerUrl);// reads text from URL
JSONObject json = new JSONObject(jsonText); // You create a json object from your string jsonText
if(json.has("onair")) { // just a simple test to check the node that you need existe
boolean value = json.getBoolean("onair"); // In the url that you gave onair value is boolean type
return value;
}
return false;
}
I will create methode using your way !
public static boolean checkIfOnline(String channel) throws IOException {
String channerUrl = "https://api.dailymotion.com/video/x3p6d9r?fields=onair";
String jsonText = readFromUrl(channerUrl);// reads text from URL
JsonParser parser = new JsonParser();
String myString =json.get("onair");
return mystring;}
Please clear my understanding why I am getting of value of company after deserialization. I know "Statics are implicitly transient, so we don't need to declare them as such."
class Employee implements Serializable {
String name;
static String company = "My Company";
public Employee(String name) {
this.name = name;
}
}
public class Test8 {
public static void main(String[] args) throws Exception {
Employee e = new Employee("John");
serializeObject(e);// assume serialize works fine
Employee e1 = deserializeObject(); // assume deserialize works fine
System.out.println(e1.name + " " + e1.company);
}
public static void serializeObject(Employee e) throws IOException {
FileOutputStream fos = new FileOutputStream("Test8.cert");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(e);
oos.flush();
oos.close();
}
public static Employee deserializeObject() throws IOException, ClassNotFoundException {
FileInputStream fis = new FileInputStream("Test8.cert");
ObjectInputStream oos = new ObjectInputStream(fis);
return (Employee) oos.readObject();
}
}
Value of static field company was set first time you used Employee class. In your case it would be in line:
Employee e = new Employee("John");
This value didn't change since it wasn't serialized and deserialized so it stayed the same, which means
System.out.println(e1.name + " " + e1.company);
prints John My Company.
But even if you remove lines
Employee e = new Employee("John");
serializeObject(e);
from your code, and invoke only
public static void main(String[] args) throws Exception {
Employee e1 = deserializeObject(); // assume deserialize works fine
System.out.println(e1.name + " " + e1.company);
}
Employee class will still be loaded inside deserializeObject (by oos.readObject() method) so its static fields will also be properly initialized to its default values.
I am serializing a hash map in my Java code and write it to a file. While deserializing, the file contains more than one values, but it returns only top most key and value pair. Can anyone tell me why? Here is my Java code for deserialization:
public static void main(String[] args) throws IOException, ClassNotFoundException {
HashMap<String, String> data = new HashMap<Integer, String>();
ObjectInputStream in = new ObjectInputStream(new FileInputStream("F:\\f.txt"));
data = (HashMap<String, String>) in.readObject();
for (Map.Entry entry : data.entrySet()) {
System.out.println("key" + entry.getKey());
System.out.println("value" + entry.getValue());
}
}
Here is my serialization code
public class SerializeObject implements Serializable {
public static void main(String[] args) throws IOException, ClassNotFoundException
{
HashMap<String,String> map = new HashMap<String,String>();
map.put("Monday","first");
map.put("Tuesday","Second");
map.put("Wednesday","Third");
FileOutputStream fout=new FileOutputStream("F:\\f.txt",true);
ObjectOutputStream out=new ObjectOutputStream(fout);
out.writeObject(map);
out.flush();
}
}
After deserializing it returns only Monday and first
You should close your streams. out.flush() might not be enough to ensure that all remaining data is written to disk. An easy way to ensure that is to use try-with-resource statements:
public static void main(String[] args) throws IOException, ClassNotFoundException
{
HashMap<String,String> map = new HashMap<String,String>();
map.put("Monday","first");
map.put("Tuesday","Second");
map.put("Wednesday","Third");
try (
FileOutputStream fout=new FileOutputStream("F:\\f.txt",true);
ObjectOutputStream out=new ObjectOutputStream(fout); )
{
out.writeObject(map);
}
}