How to clear an inputstream in java - java

I have data coming from a bluetooth device, the data is being stored in an inputstream. I am taking the data from the inputstream and generating a graphic with Jfreechart. Whenever I turn off the bluetooth device the data keeps coming from the inputstream and the graphic continues being generated.
I need the data and the graphic to stop when I turn off the bluetooth device.
I am using Java.

Every InputStream has a close() method that should do exactly what you need ... if you can detect that the device is turned off, that is.
The docs on this.

Reference link : Closing java InputStream
which resolved my problem too.
Properties props = new Properties();
InputStream fis = new FileInputStream("message.properties");
try {
props.load(fis);
//omitted.
} catch (Exception ex) {
//omitted.
} finally {
try {
fis.close();
fis=null;
} catch (IOException ioex) {
//omitted.
}
}

Related

Reading an image resource file in java

I've been searching to find out how to solve this problem for some time now, but I can't seem to find a way. I could read the image as long as it was in eclipse, but when I exported it, it was impossible. I tried with an InputStream, but that throws an IllegalArgumentException for some reason, what am I doing wrong?
InputStream iconstream = getClass().getResourceAsStream("resources/icon.png");
InputStream pigstream = getClass().getResourceAsStream("resources/pig.png");
This is for getting the resources, and here is where I read them:
try {
icon = ImageIO.read(iconstream);
pig = ImageIO.read(pigstream);
} catch(IOException e) {
e.printStackTrace();
System.err.println(e.getMessage());
} catch(IllegalArgumentException e) {
e.printStackTrace();
System.err.println(e.getMessage());
}
change
InputStream iconstream = getClass().getResourceAsStream("resources/icon.png");
to
InputStream iconstream = getClass().getResourceAsStream("/resources/icon.png");
getClass().getResourceAsStream() looks in the package of the class. You either need to add a leading / to the name or else use getClass().getClassLoader().getResourceAsStream().

Java: Can't delete local file after jsch.put

I'm having some issues with removing files after moving them to an ftp site. In a previous process I am generating files and putting them in a folder. This process should upload every file to the ftp site and then delete the local copy. For reasons I can't figure out the delete is failing but I'm not getting any sort of error message or exception. Originally I had the file.delete() call right after the ftp.put() but I moved it to it's current location thinking that maybe the file was locked by jsch and putting the call there would fix it. That doesn't seem to be the case. Ideally the call would go back there so I don't need to have two "for" loops.
If you also happen to know why the overwrite is not working that would be a bonus. When i look at the files uploaded through an actual FTP program the rights are rw-rw-rw. The existing files on the server were already uploaded through this process.
Here is the code:
JSch jsch = new JSch();
Session session = null;
try {
File sourceDir = new File(certSourceFolder);
if (!sourceDir.exists()) {
sourceDir.mkdirs();
}
session = jsch.getSession(ftpUser, ftpServer, 22);
session.setConfig("StrictHostKeyChecking", "no");
session.setPassword(ftpPassword);
session.connect();
Channel channel = session.openChannel("sftp");
channel.connect();
ChannelSftp ftp = (ChannelSftp) channel;
ftp.cd(certDestFolder);
for (File file : sourceDir.listFiles()) {
if (file.isFile()) {
try {
ftp.put(new FileInputStream(file), file.getName(), ChannelSftp.OVERWRITE);
} catch (SftpException ex) {
//The overwrite is not working. For now I'm just going to trap the error and move on. This really shouldn't happen ever since I delete the file once uploaded.
if (!ex.getMessage().equalsIgnoreCase("Permission denied"))
throw ex;
}
}
}
ftp.exit();
session.disconnect();
//TODO: this is not working. figure out why. If possible get rid of this and move the file.delete up to after ftp.put
for (File file : sourceDir.listFiles()) {
if (file.isFile()) {
file.delete();
}
}
} catch (Exception e) {
DefaultLogger.logException("CertificateFileTransfer", e);
}
}
You must close the file after using it, otherwise, it will be locked by the current using component.
Change this line:
ftp.put(new FileInputStream(file)...
To a finally clause that calling close on the stream in order to ensure the release of the file in any case (good or exception):
finally{
fileInput.close();
}
To recap:
FileInputStream fileInput = null;
try {
fileInput = new FileInputStream(file);
ftp.put(fileInput, file.getName(), ChannelSftp.OVERWRITE);
} catch (SftpException ex) {
if (!ex.getMessage().equalsIgnoreCase("Permission denied"))
throw ex;
}
finally{
if(fileInput != null){
fileInput.close();
}
}
From docs:
close() Closes this file input stream and releases any system
resources associated with the stream.

New to Java. Problems reading from file using Context and openFileInput

I've been trying to do this on my own for the past couple hours and am kinda losing it a little.
All I want to do is open a file, read it and display it to the console; that's it.
I'm using eclipse to develop for android 2.3.3.
I have tried using a bunch of different ways with code that I have found here, and on other sites. Here is what I have now and how its all called:
In the OnCreate function:
setContentView(new TestMap(this));
The testMap class:
TestMap(Context context){
super(context);
// might need to be on the panel class
loadTileFile("worldonelayout.txt", context);
in the same class:
private void loadTileFile (String filename, Context context){
FileInputStream input = null;
InputStreamReader reader = null;
char[] inputBuffer = new char[256];
String data = null;
try {
input = context.openFileInput("worldonelayout.txt");
reader = new InputStreamReader(input);
reader.read(inputBuffer);
data = new String(inputBuffer);
System.out.println(data);
Toast.makeText(context, "Text read", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(context, "Text not read", Toast.LENGTH_SHORT).show();
} finally {
try {
input.close();
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
This code doesnt work. It always hits the exception.
"/data/data/com.name.somethingiremoved/files/worldonelayout.txt (No such file or directory)".
This happens at the first CATCH. BTW my file is in the root directory: Documents\Eclipse\workspace\project\worldonelayout.txt. I can also see the file in the browser on the left
From what I have seen here and on other sites, it is something to do with the Context class being derived from the Activity? I don't want to have this code in the same class as my activity. Is there a way round this?
If you need anything more from me, let me know.
The open file is looking for a file on the phone's file system, not on the computer's. Its telling you exactly where it expects to find it - on the phone under /data/data/com.name.somethingiremoved/files/worldonelayout.txt

Serializing an ArrayList

I'm trying to write an Android game and I would like to be able to pause the game even if the user wants to return to the main menu or the activity gets killed off by the system. onSaveInstanceState doesn't seem to give me a whole lot of control as to when I can read the bundle back, plus from what I can tell, the bundle is only good for short periods of time. So I want to serialize a few ArrayLists that I have, then read them back. I don't get any compile errors nor does the program crash. But, the data either never gets written or never gets read. I'm not sure which one. My serializeData method is called in onDestroy and the deserializeData is called from onCreate. Here's my code for writing and reading the data:
public void serializeData(String filename, ArrayList<String>arrayList) {
FileOutputStream fos;
try {
fos = openFileOutput(filename, Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(arrayList);
oos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
}
#SuppressWarnings("unchecked")
private void deserializeData(String filename, ArrayList<String>arrayList){
try{
FileInputStream fis = openFileInput(filename);
ObjectInputStream ois = new ObjectInputStream(fis);
arrayList = (ArrayList<String>)ois.readObject();
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}catch(ClassNotFoundException e){
e.printStackTrace();
}
}
Any help would be greatly appreciated! Thanks in advance!
Let me tell you one thing: never use the onDestroy() method to save your data. Use onPause() or onStop() instead. You should never count on the onDestroy() method to save data or call some functions.
Use onDestroy to close connections and finish using resources and the like. If you want to read more about this you should take a look here.
Other than that your code seems fine. Just add one more thing: put a oos.flush() just above oos.close().
And don't forget to close the objectInputStream object.
I cannot see an obvious problem with that code.
I'd try adding some code after closing the ObjectOutputStream and before opening the ObjectInputStream to print out the absolute name and size of the file.
While serializing you can write to ByteArrayOutputStream and then decode the bytes into string using platform's default character set. Store this string into SharedPreferences. While deserializing, just get the bytes from string and create a ByteArrayInputStream using this and feed it to ObjectInputStream.Are you sure your activity is being killed? It might be the case that your activity is oscillating between onPasue/onResume.

Why do I get FileNotFoundException when I create and try to write to file on Android emulator?

First off, I am not trying to write to the SDCard. I want to write some information to a file that persists between uses of the app. It is essentially a file to hold favorites of the particular user. Here is what the code looks like:
try {
File file = new File("favorites.txt");
if (file.exists()) {
Log.d(TAG, "File does exist.");
fis = new FileInputStream(file);
br = new BufferedReader(new InputStreamReader(fis));
}
else {
Log.d(TAG, "File does not exist.");
return favDests;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
When running this code, we always get the "File does not exist." message in our DDMS log.
We have also tried the following code to no avail:
try {
File file = new File(GoLincoln.FAV_DEST_FILE);
fis = new FileInputStream(file);
br = new BufferedReader(new InputStreamReader(fis));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
It is this second portion of code that results in the FileNotFoundException.
I have read multiple tutorials on writing and reading files on Android and I believe I am following them pretty closely, so I am not sure why this code doesn't work successfully. I appreciate any help!
You shouldn't use the File class directly. Use Activity.getCacheDir() to get the cache dir which is specific to your application. Then use new File(cachedir, "filename.tmp") to create the file.
Preferences and SQLLite will both allow you to have persistent data without managing your own files.
To use shared preferences you grab it from your context, then you edit the values like so
mySharedPreferences = context.getSharedPreferences("DatabaseNameWhateverYouWant", 0);
mySharedPreferences.getEditor().putString("MyPreferenceName", "Value").commit();
To get a preference out
mySharedPreferences.getString("MyPreferenceName", "DefaultValue");
This is really the simplest way to do basic preferences, much easier then doing a file. More then strings are supported, most basic data types are available to be added to the Preferences class.

Categories