is there any way out that we can make the data in text file persistent? everytime a user finishes playing a game, in my program his name and respective score is written to a text file. When the next player comes the previous one gets overwritten. since am writing in write mode, I am not sure whether append mode is supported to save scores of this sort in blackberry...any suggestions are welcome
You should really use the PersistentStore to store this type of information - it's much easier to use and probably more reliable than trying to write files.
However, if you insist on writing files, here's the general code to open a file for appending:
private OutputStream openFileForWriting(String filePath) {
try {
FileConnection fconn = (FileConnection) Connector.open(filePath);
// If no exception is thrown, then the URI is valid, but the file may or may not exist.
if (!fconn.exists()) {
fconn.create(); // create the file if it doesn't exist
}
return fconn.openOutputStream(fconn.fileSize());
} catch (IOException ioe) {
System.out.println("Could not open " + filePath + " for writing");
}
return null;
}
Related
I am targeting Android API 30. My app was storing log file and taking database backup in location "/storage/emulated/0/SpecialDir/". Now I am facing access denied issue while my app was workinng fine previously.
I got an overview about scoped storage and came to know that we have some managed locaitons where we can store our data accordingly. i.e Audio, Video, Images, and Download
My question is What is the solution for existing apps that was previously saving files on "/storage/emulated/0/SpecialDir/".
Can anyone please guide me what should i do.
string dir = Path.Combine(Android.OS.Environment.ExternalStorageDirectory.ToString(), "LogFolder");
if (Directory.Exists(dir))
{
return Path.Combine(dir, "MyLogFile.txt");
}
try
{
string newDirectory = Directory.CreateDirectory(dir).FullName;
path = Path.Combine(newDirectory, "MyLogFile.txt");
System.IO.File.WriteAllText(path, "This is some testing log.");
}
catch (Exception ex)
{
string msg = ex.Message;
}
The above code is used to make 'LogFolder' if not exist and 'MyLogFile' as well. What changes do i needed to make it compatiable to Android 10. Thankyou
In Android 10, Google has introduced a new feature for external Storage. Its name is Scoped Storage. Google officially translates it as partitioned Storage, or Scoped Storage.The intent is to limit what programs can do with public directories in external storage. Partitioned storage has no effect on either the internal storage private directory or the external storage private directory.In short, in Android 10, there is no change to private directory reads and writes, and you can still use the File set without any permissions. For reading and writing to public directories, you must use the API provided by MediaStore or the SAF (storage access framework), which means you can no longer use the File set to manipulate public directories at will.
If you set targetSdkVersion above 29,you could try to add below codes into your AndroidManifest.Then you could access the File as before.
<manifest ... >
<application android:requestLegacyExternalStorage="true" ... >
...
</application>
</manifest>
Update (you could try this for public external storage ):
var path = Android.OS.Environment.GetExternalStoragePublicDirectory("LogFolder").AbsolutePath;
Java.IO.File file = new Java.IO.File(path);
if (!file.Exists())
{
file.Mkdirs();
}
try
{
FileWriter fw = new FileWriter(path + Java.IO.File.Separator + "MyLogFile.txt");
fw.Write("This is some testing log.");
fw.Close();
}
catch (Exception ex)
{
string msg = ex.Message;
}
Update for Android 11:
add MANAGE_EXTERNAL_STORAGE permission in your AndroidManifest.
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
in your activity:
if (Environment.IsExternalStorageManager)
{
var path = Android.OS.Environment.GetExternalStoragePublicDirectory("LogFolder").AbsolutePath;
Java.IO.File file = new Java.IO.File(path);
if (!file.Exists())
{
file.Mkdirs();
}
try
{
FileWriter fw = new FileWriter(path + Java.IO.File.Separator + "MyLogFile.txt");
fw.Write("This is some testing log.");
fw.Close();
}
catch (Exception ex)
{
string msg = ex.Message;
}
}
else
{
StartActivityForResult(new Intent(Settings.ActionManageAllFilesAccessPermission), 0);
}
I'm trying to write a java program that reacts if a new entry occures in the file C:/xampp/apache/logs/access.log in order to recognize a new request to my Apache Server.
I used the following code:
public static void monitor() throws IOException {
WatchService watcher = FileSystems.getDefault().newWatchService();
File file = new File("C:/xampp/apache/logs/");
Path dir = file.toPath();
dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY, OVERFLOW);
for (;;) {
// wait for key to be signaled
WatchKey key;
try {
key = watcher.take();
} catch (InterruptedException x) {
return;
}
for (WatchEvent<?> event : key.pollEvents()) {
WatchEvent.Kind<?> kind = event.kind();
// get file name
#SuppressWarnings("unchecked")
WatchEvent<Path> ev = (WatchEvent<Path>) event;
Path fileName = ev.context();
System.out.println(kind.name() + ": " + fileName);
if (kind == OVERFLOW) {
continue;
} else if (kind == ENTRY_CREATE) {
System.out.println("entry created occured");
// process create event
} else if (kind == ENTRY_DELETE) {
// process delete event
} else if (kind == ENTRY_MODIFY && fileName.toString().equals("access.log")) {
System.out.println("entry modified occured");
// process modify event
}
}
// Reset the key -- this step is critical if you want to
// receive further watch events. If the key is no longer valid,
// the directory is inaccessible so exit the loop.
boolean valid = key.reset();
if (!valid) {
break;
}
}
}
But it does not recognize the change in access.log until I manually open the file. Is there something wrong with my code?
There are differents options.
There are two questions that can be kind of similiar, the only difference is that they want to check a whole direcotry instead of just a file, but you could adapt the code to detect if the modified file is the one that you want.
Watching a Directory for Changes in Java
Java detect changes in filesystem
For a specific solution I've found
http://www.rgagnon.com/javadetails/java-0490.html
This code launches a thread that checks the lastModified value of the file, if it's different from the previous one, it means that the file has been modified. I don't know if it's very efficient, check them out.
I am running Eclipse Java EE and tomcat for running my webapp. I used the following code to store an image file to the upload/images/profilepics directory:
public String uploadPhoto() {
try {
//get path to upload photo
String filePath = servletRequest.getSession().
getServletContext().getRealPath("/uploads/profilepics");
System.out.println("Server path:" + filePath);
//creating unique picture name
Map sess = (Map) ActionContext.getContext().get("session");
Integer uid = (Integer) sess.get("uid");
String profilePictureName = uid + "-" +
MyUtilityFunctions.createVerificationUrl() + this.userImageFileName;
//update user record
//tobe done
String imgUrl = filePath + profilePictureName;
ViewProfileModel pofilePictureUpdate = new ViewProfileModel();
pofilePictureUpdate.updateUserPhotoUrl(imgUrl, uid);
//create new File with new path and name
File fileToCreate = new File(filePath, profilePictureName);
//copy file to given location and with given name
FileUtils.copyFile(this.userImage, fileToCreate);
} catch (Exception e) {
e.printStackTrace();
addActionError(e.getMessage());
return INPUT;
}
return SUCCESS;
}
after printing filePath I got the following result:
Server Path: /home/bril/webspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/picvik/uploads/profilepics
Now the problem is, I am not able to get the image or if I give the same url to <img src=""> nothing is getting displayed.
Please correct where I am doing wrong.
There are suggestions:
there are lots of reason, that you shouldn't save user images in this way, just like #DaveNewton mentioned in another question. There
are some post to help you make your decision:
Post1
Post2
My personal opinion is to save them into DB, because you don't want
to let your user lost their images.
If you need access session, you can check out SessionAware. This should be a better way to access session.
You are using tomcat as application container, you can configure the server to use its local installation, which makes you easier to track the problem in this case. check out this picture below
Back to your question, There are different ways to do this:
if you cannot find the image user just uploaded, you can check it
manual, see 3.
Otherwise, you could try <img src="/uploads/profilepics/<s:property
value='profilePictureName'/>"
Or you can get this picture using stream, here is the snippet:
JSP:
<img src="
<s:url var="profilePic" action="customer-image-action">
<s:param name="uid" value="%{uid}"/>
</s:url>
" alt="kunden logo" />
Action:
public String execute() throws Exception {
// filename = somehow(uid);
HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
imgPath = request.getSession().getServletContext().getRealPath("/uploads/profilepics/")+filename;
log.debug("context-path: " + imgPath);
try {
inputStream = FileUtils.openInputStream(new File(imgPath));
} catch (IOException e) {
log.error(e.getCause(), e);
}
return SUCCESS;
}
I pretty much copied this code right out of the MDN File I/O page.. except I added an if statement to check if the file exists already and if it does, read it instead.
Components.utils.import("resource://gre/modules/NetUtil.jsm");
Components.utils.import("resource://gre/modules/FileUtils.jsm");
var file = Components.classes["#mozilla.org/file/directory_service;1"].
getService(Components.interfaces.nsIProperties).
get("Desk", Components.interfaces.nsIFile);
file.append("test.txt");
if (!file.exists()) {
this.user_id = Math.floor(Math.random()*10001) +'-'+ Math.floor(Math.random()*10001) +'-'+ Math.floor(Math.random()*10001) +'-'+ Math.floor(Math.random()*10001);
var ostream = FileUtils.openSafeFileOutputStream(file)
var converter = Components.classes["#mozilla.org/intl/scriptableunicodeconverter"].
createInstance(Components.interfaces.nsIScriptableUnicodeConverter);
converter.charset = "UTF-8";
var istream = converter.convertToInputStream(this.user_id);
// The last argument (the callback) is optional.
NetUtil.asyncCopy(istream, ostream, function(status) {
if (!Components.isSuccessCode(status)) {
alert('Error '+ status);
return;
}
alert('File created');
});
} else
{
NetUtil.asyncFetch(file, function(inputStream, status) {
if (!Components.isSuccessCode(status)) {
alert('error '+ status);
return;
}
// The file data is contained within inputStream.
// You can read it into a string with
this.user_id = NetUtil.readInputStreamToString(inputStream, inputStream.available());
});
alert('File exists already, do not create');
}
alert(this.user_id);
It creates the file just fine, I can open it and read it. If the file already exists however, it does not populate this.user_id.. just equals null. So my issue is specifically with reading the file.
File reading in your code works asynchronously - meaning that your code completes (including the alert() call which will show that this.user_id is null), then at some point the callback from NetUtil.asyncFetch() gets called with the data. Until that happens this.user_id won't be set of course. If you move alert(this.user_id) into the callback function it should show the correct value.
Note that it is highly recommended to keep file I/O operations asynchronous because they might take significant time depending on the current state of the file system. But you have to structure your code in such a way that it doesn't assume that file operations happen immediately.
Can any one please tell me the process through which I can open a photo gallery in the blackberry application to choose a photo to upload, is there any file uploading control in the blackeberry 5.0 and also tell me the process to save the photo from the blackberry application to the remote server using HttpWebRequest.
Thanks
Their is nice way which i have done. Just get selected image from the phone through file browser or file io method than convert it to a byte array than just encode it to base64 String and send this string to the server by http request.
and at server side just do opposite.
final byte[] chunk;
chunk = new byte[actualSize];
try {
int bytesRead = in.read(chunk);
fconn.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try
{
String encodedStr = Base64OutputStream.encodeAsString(chunk, 0, chunk.length,false,false);
}