Exception java.lang.NullPointerException - java

Iam working in a desktop application for windows version using java. In my application there is a requirement to search all .php
i use recursive methods;
and REGEX
my code :
import java.io.File;
public class Copier {
public static void find(String source,String rep)
{
File src=new File(rep);
if(src.exists() && src.isDirectory())
{
String[] tab=src.list();
for(String s:tab)
{
File srcc=new File(rep+"\\"+s);
if(srcc.isFile())
{
if(srcc.getName().matches(".*"+source+"$"))
System.out.println(s);
}
else
find(source,srcc.getAbsolutePath());
}
}
}
public static void main(String[] args)
{
find(".php","C:\\");
}
}
But i have this exception :
Exception in thread "main" java.lang.NullPointerException
at Copier.find(Copier.java:11)
at Copier.find(Copier.java:21)
at Copier.main(Copier.java:28)

src.list() returns null. It probably happens because you (current user) does not have access rights to the directory. I guess it is about C:\ (the root directory of disk C). This often happens especially on Windows 7.
First try to debug your code using directory where you have access rights. Then fix your code to care about nulls. Then try to run your program as an administrator.

Change main like below, for debugging purpose.
public static void main(String[] args)
{
try {
find(".php","C:\\");
} catch (Exception e) {
e.printStackTrace();
}
}
And add a null check in
if (src != null && src.exists() && src.isDirectory())
Edit:
Below works fine for me, (I am using windows 7).
import java.io.File;
public class Copier {
public static void find(String source,String rep) {
File src = new File(rep);
if (src!= null && src.exists() && src.isDirectory()) {
String[] tab = src.list();
if (tab != null) {
for(String s : tab) {
File srcc = new File(rep+"\\"+s);
if (srcc.isFile()) {
if (srcc.getName().matches(".*"+source+"$")) {
System.out.println(s);
}
} else {
find(source,srcc.getAbsolutePath());
}
}
} else {
//System.out.println(" list is null");
}
}
}
public static void main(String[] args) {
try {
find(".java", "C:\\");
} catch (Exception e) {
e.printStackTrace();
}
}
}

Related

window could not strat the "sample service"[myservice name] service on llocal computer

I created a sample java service creation code, after done the jar creation , exe.. done the window service creation using the sc create command, my service created successfully, but while trying to start the service I'm getting this error,
"Error 1053:the service did not respond to the start or control request in a timely fashion"
this is my java code-[is this due to command line argument passing?]
public class LDAP_TestConnection {
private static boolean stop = false;
public static void start(String[] args) {
System.out.println("start");
while (!stop) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
System.out.println("running");
}
}
public static void stop(String[] args) {
System.out.println("stop");
stop = true;
}
public static void main(String[] args) {
if (args == null){
System.out.println("Params are required"+args.length);
}else{
if ("start".equals(args[0])) {
start(args);
} else if ("stop".equals(args[0])) {
stop(args);
}
}
}
}

How to read file from storage in Xamarin

I made a DRM media player app in Xamarin which drops course.licns and pass.licns files in internal memory in app directory for reading correct key.
It's working fine in Android 10 but it's not working in above versions like Android 11 and 12 when I put course name and key then app added both files but can't read it again when I want to play a video. The same thing is working fine on lower versions.
My code:
using System;
using System.Text;
using System.IO;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
using Android.OS;
namespace MediaElement
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class Add : ContentPage
{
public Add()
{
InitializeComponent();
}
async void Appears(object sender, EventArgs e)
{
try
{
this.FindByName<Entry>("ID").Text =Helper. GetIMEI();
}
catch (Exception e2)
{
await DisplayAlert("Error!", e2.Message, "Ok");
}
}
public static string Pass()
{
return Path.Combine((string)System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "pass.licns");
//return Path.Combine((string)System.Environment.GetFolderPath(System.Environment.SpecialFolder.LocalApplicationData), "pass.licns");
}
public static string Course()
{
//return Path.Combine((string)System.Environment.GetFolderPath(System.Environment.SpecialFolder.LocalApplicationData), "course.licns");
return Path.Combine((string)System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "course.licns");
}
void Register(object sender, EventArgs e)
{
try
{
string key = this.FindByName<Entry>("Key").Text.Trim();
string Name = this.FindByName<Entry>("Name").Text.Trim();
if (key== string.Empty || Name == string.Empty) { throw new Exception("Key or Name is empty"); }
if (!IsBase(key)) { throw new Exception("Invalid key!"); }
if (!IsValidID(key)) { throw new Exception("This key is not designed for your ID."); }
if (File.Exists(Pass()) && File.Exists(Course()))
{
if (File.ReadAllText(Pass()).Contains(key) || File.ReadAllText(Course()).Contains(Name)){ throw new Exception("Key or Course Already exists."); }
}
File.AppendAllText(Pass(), key+",");
File.AppendAllText(Course(), Name + ",");
DisplayAlert("Success", "License added successfully.", "Ok");
}
catch (Exception e2)
{
DisplayAlert("Error", e2.Message, "Ok");
}
}
bool IsBase(string base64)
{
try
{
if (base64 == Convert.ToBase64String(Convert.FromBase64String(base64))) { return true; }
}
catch (Exception)
{
}
return false;
}
public static bool IsValidID(string key)
{
return Encoding.ASCII.GetString(MainPage.Decrypt(Convert.FromBase64String(key),Helper. IDkey)).Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries)[0].ToString() == Helper. GetIMEI();
}
}
}
Note:
I don't want to use All file access permissions due to so many restrictions in Google Play Store and my App is only accessing a particular file. Is there a proper way for upper versions?

Populate a Java File object at compile time

I have a third-party library that requires the populating of a java File object at runtime. I have extended this code, but I do not need the file-related part. However, for my purposes, I am forced to create and use the File object and read from it.
Is there a way I can have the binary equivalent of an already-read file available at runtime? Or is there a way to have a file as byte-code already available for a File object? Please assume with my situation that going to a file-system to retrieve and open a file is not an option.
Thanks for any insights!
You can create a temp file and delete after your program finishes.
import java.io.*;
import java.nio.file.*;
public class Program {
public static final File EMPTY_FILE = createTmpFile("empty.dat");
private static final File createTmpFile(final String filename) {
String tmpDir = System.getProperty("java.io.tmpdir");
Path filePath = Paths.get(tmpDir, filename);
return filePath.toFile();
}
public static void main(String[] args) {
try {
// Do stuff...
System.out.println(EMPTY_FILE.getCanonicalPath());
Thread.sleep(2000);
} catch (IOException | InterruptedException e) {
e.printStackTrace();
} finally {
// Cleanup...
EMPTY_FILE.delete();
}
}
}
If you need a PHYSICAL file on they system, you can create it like so:
import java.io.*;
import java.nio.file.*;
public class Program {
public static final String TMP_DIR = System.getProperty("java.io.tmpdir");
public static final File EMPTY_FILE = createTmpFile("empty.dat");
private static final File createTmpFile(final String filename) {
Path filePath = null;
try {
byte[] data = { 0 }; // Write a single byte of data
filePath = Files.write(Paths.get(TMP_DIR, filename), data);
} catch (IOException e) {
e.printStackTrace();
}
return filePath.toFile();
}
public static void main(String[] args) {
try {
// Do stuff...
System.out.println(EMPTY_FILE.getCanonicalPath());
Thread.sleep(2000);
} catch (InterruptedException | IOException e) {
e.printStackTrace();
} finally {
// Cleanup...
EMPTY_FILE.delete();
}
}
}

default behavior if command line argument not provided

I have written a java code to create a file if file name is provided in command line argument, if command line argument is not entered it will create file in default folder
import java.io.File;
import java.io.IOException;
public class Outputlogs {
private final String path = "C:/temp/logs.txt";
public void createLogFile(String fileName)
{
if(fileName != null && !fileName.isEmpty())
{
File yourFile = new File(fileName);
if(!yourFile.exists()) {
try {
yourFile.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
else
{
File yourFile = new File(path);
if(!yourFile.exists()) {
try {
yourFile.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
public class MainClass()
{
public static void main(String[] argv)
{
String fileName = argv[0];
Outputlogs logs= new Outputlogs();
logs.createLogFile(fileName);
}
If i am providing command line arguments, its successfully creating the file but if command line argument is not entered, i am getting java.lang.ArrayIndexOutOfBoundsException
How to achieve my scenario if command line argument is not entered it should create default folder. Please help
Something like this:
public static void main(String[] args) {
if (args.length > 0)
createLogFile(args[0]) ;
}
I'm assuming that at some point, you are setting filename = args[0], otherwise you wouldn't be getting an array access error. If no argument is provided, the array args will be null, so accessing args[0] will return an ArrayIndexOutofBounds exception. Just check the length first:
if(args.length > 0)
fileName = args[0];
else
fileName = path;
Then you can combine your if/else statement into a single statement since at this point it filename will be either the argument or your default path:
File yourFile = new File(fileName);
if(!yourFile.exists()) {
try {
yourFile.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
This code works.
import java.io.File;
import java.io.IOException;
public class Test {
private static final String path = "C:/temp/logs.txt";
public static void main(String[] args) {
if(args.length > 0) {
createLogFile(args[0]);
} else {
createLogFile(path);
}
}
public static void createLogFile(String fileName)
{
File f = new File(fileName);
if(!f.exists()) {
try {
f.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
argv[0] means the first element in the argument-list (Array), so you have to check if there is at least one argument provided.
You can check the amount of items in the array with array.length, so everything above 0 will tell you that you can access the first (or second,third) argument.
public static void main(String[] argv)
{
String fileName = (argv.length > 0) ? argv[0]:path; // changed
Outputlogs logs= new Outputlogs();
logs.createLogFile(fileName);
}
This line will check if the length of the array is above 0 set the fileName to argv[0] if it is or take the path variable if it isn't.

In a program if we keep system.exit(0) ,what will happen and what is the console output

i have a progam like this
class A {
public void test1(String s1) {
try {
System.exit(0);
} catch (Exception ex) {
ex.printStackTrace();
} finally {
System.out.println("from finally");
}
}
public void test2(String s2) {
// some text.....
}
}
In the below class
class Manager {
public static void main(String[] args) {
A a1 = new A();
a1.test1("test1");
a1.test2("test2");
}
}
I want a detailed answer of flow of the program after calling a1.test1
control will enter to the a2.test2 in Manager class or any other? Please clarify my doubt.
Once you hit System.exit(0) the program is done. It terminates.

Categories

Resources