I have problem with my groovy script. I'm reading content from registerFile and I want to catch Exception when file is not found. Nevertheless below function doesn't throw exception even if registerfile does not exist, why?
Fragment of my code:
def registerFile
static void main(def args) {
Agent agent = new Agent()
agent.findSmth()
}
Agent() {
registerFile = new File(/path/toFile)
}
def findSmth() {
def s
try {
def lines = registerFile.readLines()
def numbers = lines.get(lines.size() - 1).findAll(/\d+/)*.toInteger()
s = numbers.get(numbers.size() - 1)
} catch (Exception e) {
println(e) //why not print that file doesn't exist?
} finally {
return s
}
}
I'm assuming that the above code is inside the class Agent.
As soon as you execute an operation on a non-existing file, an exception is thrown; so your catch statement should catch the Exception.
Are you sure that no such file exists in the path that you mentioned?
Related
try{
if ($originalfile=='sample_upload.csv')
) {
$out.='file uploaded';
}
$out.=__('MESSAGES.error_1')."\n";
$this->error($out);
return false;
....
// code to open file and read and save
}catch (\Exception $e){
}
If the file is with correct name still it puts error_1 message, I want if file is with wrong name it should exit and go to catch block or if it gets error further in reading and saving file it should again go to catch block.
I'm newbie in Android development and doing on my first Android project and faced with .txt file handling.
I succesfully created a txt file on Android Emulator, which is stored in: /storage/emulated/0/Android/data/com.example.test/files/test.txt
My problem is, I don't know how to test with code if this file exists. I write next few lines, which I found on the Internet:
fun checkIfFileExists() {
val fileName2 = "test.txt"
var file = File(filesDir, fileName2)
var fileExists = file.exists()
if(fileExists) {
println("File exists")
}
else {
println("File doesn't exists")
}
}
Function for file saving:
btnSave.setOnClickListener(View.OnClickListener {
val file:String = fileName.text.toString()
val data:String = fileData.text.toString()
val fileOutputStream:FileOutputStream
try {
fileOutputStream = openFileOutput(file, Context.MODE_PRIVATE)
fileOutputStream.write(data.toByteArray())
}catch (e: FileNotFoundException){
e.printStackTrace()
}catch (e: NumberFormatException){
e.printStackTrace()
}catch (e: IOException){
e.printStackTrace()
}catch (e: Exception){
e.printStackTrace()
}
Toast.makeText(applicationContext,"data save",Toast.LENGTH_LONG).show()
fileName.text.clear()
fileData.text.clear()
})
But it always prints "File doesn't exists", although I checked myself and file exists.
Hope someone knows what I did wrong.
You instantiated the file with only the file name and no path, so how can it know where to look? On Android you don't want to be working with the absolute paths but with what the Context gives you.
Not sure how you created your original file, but assuming it was saved to internal storage, you would do this (getFilesDir() is a Context method, so will be available if calling from an Activity):
var file = File(getFilesDir().getAbsolutePath(), fileName2)
I am writing a custom fuse Mirror File System (in Ubuntu using FUSE-JNA). By mirror I mean, It will read from and write into a directory of local file system.
I implemented getattr, create, and read operation as below. All these work perfectly.
...
private final String mirroredFolder = "./target/mirrored";
...
...
public int getattr(final String path, final StatWrapper stat)
{
File f = new File(mirroredFolder+path);
//if current path is of file
if (f.isFile())
{
stat.setMode(NodeType.FILE,true,true,true,true,true,true,true,true,true);
stat.size(f.length());
stat.atime(f.lastModified()/ 1000L);
stat.mtime(0);
stat.nlink(1);
stat.uid(0);
stat.gid(0);
stat.blocks((int) ((f.length() + 511L) / 512L));
return 0;
}
//if current file is of Directory
else if(f.isDirectory())
{
stat.setMode(NodeType.DIRECTORY);
return 0;
}
return -ErrorCodes.ENOENT();
}
below create method creates new file in mirrored folder
public int create(final String path, final ModeWrapper mode, final FileInfoWrapper info)
{
File f = new File(mirroredFolder+path);
try {
f.createNewFile();
mode.setMode(NodeType.FILE, true, true, true);
} catch (IOException e) {
e.printStackTrace();
}
return 0;
}
read method reads file from mirrored folder
public int read(final String path, final ByteBuffer buffer, final long size, final long offset, final FileInfoWrapper info)
{
String contentOfFile=null;
try {
contentOfFile= readFile(mirroredFolder+path);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
final String s = contentOfFile.substring((int) offset,
(int) Math.max(offset, Math.min(contentOfFile.length() - offset, offset + size)));
buffer.put(s.getBytes());
return s.getBytes().length;
}
But my write operation is not working.
Below is my Write method, which is incomplete.
public int write(final String path, final ByteBuffer buf, final long bufSize, final long writeOffset,
final FileInfoWrapper wrapper)
{
return (int) bufSize;
}
When I run it in Debugger mode, the path arguments shows Path=/.goutputstream-xxx (where xxx is random alphanumeric each time write method is called)
Please guide me how to correctly implement write operation.
Just write to the filename you're given. How do I create a file and write to it in Java?
The reason you're seeing path=/.goutputstream-xxx is because of https://askubuntu.com/a/151124. This isn't a bug in fuse-jna.
I run all my scripts through a .suite-file roughly in the following form:
_include("variables.sah");
_include("functions.sah");
$a = 0;
while($a<3) {
try {
_navigateTo($loginpage);
login($user, $password);
myFunction();
$a = 3
}
catch (e){
_navigateTo($loginpage);
login($user, $password);
//undo changes made by myFunction()
...
$a++;
if($a<3) {
_log("Try again");
}
else {
_log("Skip to next script");
}
}
}
function myFunction() {
//do this
...
}
Now all this runs perfectly fine, except for one thing: it doesn't repeat when it encounters a missing element which under normal circumstances would abort all scripts. It simply ignores the error and moves on to the next line of the suite. How do I make my script retry up to 2 times before moving on, if I don't know which part (if any) is going to fail and when?
Your code looks fine I guess.
One thing I can think of is that the exception is thrown in the catch block.
I made a simple script which works as intended:
var $errors = 0;
function trySet() {
try {
_setValue(_textbox("does not exist"), "");
} catch ($e) {
$errors++
_alert($errors);
}
}
for (var $i = 0; $i < 3; $i++) {
trySet();
}
Better figure out where exactly your script runs into problems and handle them with separate try-catch blocks accordingly. How you handle the exceptions is up to you but I guess it would be something like:
try {
login()
} catch ($e) {
// login failed, try again
}
try {
myfunction()
catch($e) {
revertMyFunction()
//try again
}
Maybe define your own exceptions to differently react to errors, have a look at this for more info on custom exceptions: Custom Exceptions in JavaScript
Regards
Wormi
Has anyone EVER managed to use a windows 8 app to copy files from a unc dir to a local dir ?
According to the official documentation here
It is possible to connect to a UNC path
I am using the std FILE ACCESS sample and have changed one line of code to read as below
I have added all the capabilities
Added .txt as a file type
The UNC path is read write to everyone and is located on the same machine..
But I keep getting Access Denied Errors.
Can anyone possibly provide me with a working example
This is driving me mad and really questioning the whole point of win 8 dev for LOB apps.
TIA
private async void Initialize()
{
try
{
//sampleFile = await Windows.Storage.KnownFolders.DocumentsLibrary.GetFileAsync(filename);
string myfile = #"\\ALL387\Temp\testfile.txt";
sampleFile = await Windows.Storage.StorageFile.GetFileFromPathAsync(myfile);
}
catch (FileNotFoundException)
{
// sample file doesn't exist so scenario one must be run
}
catch (Exception e)
{
var fred = e.Message;
}
}
I have sorted this out and the way I found best to do it was to create a folder object
enumnerate over the files in the folder object
copy the files one at a time to the local folder then access them
It seems that you can't open the files, but you can copy them. ( which was what I was trying to achieve in the first place )
Hope this helps
private async void Initialize()
{
try
{
var myfldr = await Windows.Storage.StorageFolder.GetFolderFromPathAsync(#"\\ALL387\Temp");
var myfiles = await myfldr.GetFilesAsync();
foreach (StorageFile myfile in myfiles)
{
StorageFile fileCopy = await myfile.CopyAsync(KnownFolders.DocumentsLibrary, myfile.Name, NameCollisionOption.ReplaceExisting);
}
var dsd = await Windows.Storage.KnownFolders.PicturesLibrary.GetFilesAsync();
foreach (var file in dsd)
{
StorageFile sampleFile = await Windows.Storage.StorageFile.GetFileFromPathAsync(file.Path);
}
}
catch (FileNotFoundException)
{
// sample file doesn't exist so scenario one must be run
}
catch (Exception e)
{
var fred = e.Message;
}
}