Input Stream not working in command prompt - java

Hi Ive made a Java program which read lines from a CSV as data records. The problem im getting is the program works perfectly in eclipse console, however when I try to run the problem from cmd using Java compiler I doesnt work where my code specifies the location of the CSV file its show a error there as unknown. Ive tried everything such as moving the file into another package or using some other code to read the file Im getting the same result which is in eclipse it works but in the actual cmd it not working. Bellow is the ERROR and the method which reads the file.
java.io.FileNotFoundException: src\PostCodeENW.csv (The system cannot find the path specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
at Java.io.FileReader.<init>(Unknown Source)
public void loadfile() {
System.out.println(System.getProperty("user.dir"));
String csvFile = "src/PostcodeENW.csv";
BufferedReader br = null;
String line = "";
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
String[] ar = line.split("/");
PostCode = ar[0].trim().replaceAll(" ", " ");
String[] ar1 = PostCode.split("\\s");
String PostCodeP1 = ar1[0];
String PostCodeP2 = ar1[1];
int Easting = Integer.parseInt(ar[1]);
int Northing = Integer.parseInt(ar[2]);
String Ward = ar[3];
Location geo = new Location(PostCodeP1, PostCodeP2, Easting, Northing, Ward);
map.put(geo.getkey(), geo.getValue());
// System.out.println(PostCodeP1 + " " + PostCodeP2 + " " + Easting + " " + Northing + " " + Ward);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println("Done Adding all records");
System.out.println("Database currently holds: " + map.size()); //Test how much elements are currently in the HashMap
}

Where are you running the java file from? It's looking for a folder "src" in the current directory, then a file "PostcodeENW.csv" in the folder "src".
So if the command line is in a different directory to where that folder and file are located it would give you an error.
Try to run the java file in the same directory as where the folder "src" is located
In command line change directory to the eclipse workspace using cd %HOMEPATH%/Documents/workspace
If the eclipse workspace is in your user's folder, in your documents, in a folder called workspace.

Once compiled, the src path will no longer exist. As I understand eclipse, it will only jar class files from the src folder, this means, once compiled and packaged, it's unlikely that the file PostcodeENW.csv will even exist.
Two things you need to try,
First, move the PostcodeENW.csv file into the resources directory within your project
Once build and a packaged, eclipse will include the contents of the resources directory within the jar. This means that these resources will no longer be accessible as files,but will become embedded resources
Secondly, change your code so that when you read the file, you read it as an embedded resource, for example
String csvFile = "/PostcodeENW.csv";
//...
br = new BufferedReader(new InputStreamReader(getClass().getResourceAsInputStream(csvFile)));
Nb- I don't use eclipse, so I'm going what I understand needs to be done, but these are the basic ideas ;)

Related

Remote Machine running JVM needs to publish Git Commit Hash, deployment done with Gradle. NOT ANDROID

Every answer I have found related to this subject has been for android specifically.
What I have been able to do so far is upon build - in the build.gradle file get the Git Commit Hash and then put it in either the Manifest Files or under a "Resources" Folder within the bundles.
task create_gitCommit << {
if (project.getName().equals("com.freewire.mobi.unitconfigurationimpl")) {
String s = null;
String temp = null;
try {
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec("git rev-parse --short HEAD");
System.out.print("The following the output of the pwd command ")
System.out.println(rt.exec("pwd"))
System.out.println(System.getProperty("user.dir"))
System.out.println(GroovySystem.version)
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(proc.getInputStream()));
// read the output from the command
System.out.println("Here is the standard output of the command:\n");
if ((temp = stdInput.readLine()) != null) {
s = temp;
System.out.println(s);
File file = new File("com.freewire.mobi.unitconfigurationimpl/src/main/resources/gitCommitHash.txt") {}
file.createNewFile();
file.write s
}
} catch (IOException e) {
System.out.println("EXCEPTION CAUGHT, something is not going correct");
System.out.println(e.toString());
}
}
}
The issue is, once the code is running on the virtual machine, I have tried to access the file path and then publish the variable. But I don't think the file structure is the same on the remote machine as on my local.
private String getGitTextFilePath() throws Exception {
Resources.toString(Resources.getResource(fileContents),
Charsets.UTF_8);
ClassLoader classloader =
Thread.currentThread().getContextClassLoader();
InputStream is =
classloader.getResourceAsStream("gitCommitHash.txt");
InputStreamReader streamReader = new
InputStreamReader(is, StandardCharsets.UTF_8);
BufferedReader reader = new
BufferedReader(streamReader);
for (String line; (line = reader.readLine()) != null;) {
System.out.println(line);
}
System.out.println(is.toString());
LOG.info("GIT TEXT file path " +
is.toString());
return is.toString();
}
public String getGitCommitHash() throws Exception{
String everything = "Fake";
String path = getGitTextFilePath();
LOG.info("Working Directory = " +
System.getProperty("user.dir"));
try{
LOG.info("Inside Try 1");
LOG.info(fileContents);
BufferedReader br = new BufferedReader(new
FileReader(path));
LOG.info("Inside Try 2");
StringBuilder sb = new StringBuilder();
String line = br.readLine();
LOG.info("Inside Try 3");
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
everything = sb.toString();
br.close();
LOG.info("Inside the try: " + everything);
return everything;
}
catch(IOException e){
System.out.println("Something went wrong with trying
to read the Git Commit Hash File :,)");
}
return everything;
Option 1 - is to figure out how to find out what that file structure is and harvest the GitCommitHash I have placed in the specified folders.
Option 2 - is there a way to get the Git Commit Hash remotely? It's easy on my machine as the folder I'm in when making the build is connected to the repo. Is it possible to get the Commit Hash from the remote machine within the Java code itself?.
tl;dr - in the build.gradle I can put Git Commit Hash into a file in the correct bundle I want. Either under a resources folder, or in Manifest file. This works.
However, once the code is deployed on the remote server https://www.eurotech.com/en/products/iot/multi-service-iot-edge-gateways/reliagate-20-25, I don't know how to access that file. How do I get the file structure? Or can I somehow access Git from the remote server using Java to get the Git Commit Hash.

Java Program That Deletes Itself - Not Working

I'm trying to create a program that creates a copy of itself and deletes the original project folder.
(FYI: Project has its own JRE inside it)
(FYI: This program runs on Windows)
So:
To be able to do that, other than my primary main method, there is a second main method in the class called SelfUpdater.
Inside my main thread I copy the project to a second folder.
And then run the SelfUpdater's main method inside this second project folder:
This should mean that I'm running a whole new instance, totally unrelated to the first java.exe (which already gets closed with system.exit(0) as soon as new instance starts).
But when I try to delete the first folder, I get the error "Error deleting old client.java.io.IOException: Unable to delete file". Actually It deletes some of the files, but I can't delete Application.exe and its lib folder.
Its folder is not open in windows. It is not being used by anything else. I can't delete the file manually either (Windows says it is in use). And as soon as the second java.exe is terminated, I can delete it.
I can't give a total working example, But my in my main thread I call this following method:
public static void selfUpdate() {
try {
String separator = System.getProperty("file.separator");
String classpath = System.getProperty("java.class.path");
String rootPath = System.getProperty("user.dir");
String path = null;
File parentFolder = null;
File originalClientFolder = new File(rootPath);
parentFolder = originalClientFolder.getParentFile();
File secondClientFolder = new File(parentFolder.getAbsolutePath() + separator + "runLAST");
FileUtils.copyDirectory(originalClientFolder, secondClientFolder);
path = secondClientFolder.getAbsolutePath() + separator + "jre8" + separator + "bin" + separator + "java";
ProcessBuilder processBuilder = new ProcessBuilder(path, "-cp", classpath, SelfUpdater.class.getName(), downloadURL, rootPath);
processBuilder.directory(secondClientFolder);
processBuilder.start();
System.exit(0);
} catch (Exception ex) {
}
}
And my SelfUpdater class' main is:
public static void main(String[] args) {
try {
String originalClientFolderPath = args[1];
//
File oldClientFolder = new File(originalClientFolderPath);
System.out.println("Deleting old client recursively. Folder: " + oldClientFolder.getAbsolutePath());
try {
FileUtils.deleteDirectory(oldClientFolder);
} catch (Exception ex) {
}
}
}
Appearently, I forgot to change the classpath.
I'm thinking about leaving the question, since people may need such code part.
But at the end, method that's being called is changed to this:
public static void selfUpdate() {
try {
String separator = System.getProperty("file.separator");
String classpath = System.getProperty("java.class.path");
String rootPath = System.getProperty("user.dir");
String path = null;
File parentFolder = null;
File originalClientFolder = new File(rootPath);
parentFolder = originalClientFolder.getParentFile();
File secondClientFolder = new File(parentFolder.getAbsolutePath() + separator + "runLAST");
FileUtils.copyDirectory(originalClientFolder, secondClientFolder);
// ADDED: --------------------------------------------------------
String origialClientFolderName = originalClientFolder.getName();
classpath = classpath.replace(origialClientFolderName, "runLAST");
// ---------------------------------------------------------------
path = secondClientFolder.getAbsolutePath() + separator + "jre8" + separator + "bin" + separator + "java";
ProcessBuilder processBuilder = new ProcessBuilder(path, "-cp", classpath, SelfUpdater.class.getName(), downloadURL, rootPath);
processBuilder.directory(secondClientFolder);
processBuilder.start();
System.exit(0);
} catch (Exception ex) {
}
}

Read and Write files to package in project on Windows and Mac in Java

I am so sorry if this has been posted before.
What I am trying to do is write and read a simple string to a file located in one of the packages in my project. Inside Source Packages I have a package called "resources". Here i want to read a file called myfile.txt, do some stuff with it and save it again as newmyfile.txt. Just simple reading and storing of CSV data.
I have created a reader, which looks like this:
public BufferedReader getFileReader(String fileNameWithExtension, String sourcePackage) {
try {
String file = "/" + sourcePackage + "/" + fileNameWithExtension;
BufferedReader br = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream(file)));
return br;
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
return null;
}
}
This works fine on my Mac. Reading up on this i find out that i have to use File.separator in order to get it to work on all operating systems. So i change this, and still it don´t work. Somewhere it is said that a relative path always starts with / regardless of operating system when using relative paths, and other places ../. As a complete newbie on file storage on Java, I am confused.
There is also a lot of ways to read and write files, and I don´t know what method to choose, and why.
What is the best way for me to read and create files where all I want to do is save one long string, or an array of strings?
I have busy with other things but have now, with help from you, found a solution that works on mac and windows.
For some weird reason, String file = "/" + sourcePackage + "/" + fileNameWithExtension;is the only thing that works for reading on my mac. Suddenly (no code changes done) it started to work on windows as well. I do not know why. So working code for getting a reader is now:
public BufferedReader getFileReader(String fileNameWithExtension, String sourcePackage) {
try {
String file = "/" + sourcePackage + "/" + fileNameWithExtension;
BufferedReader br = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream(file)));
return br;
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
return null;
}
}
For writing to files in the resourses folder, i used:
public BufferedWriter getFileWriter(String fileNameWithExtension, String sourcePackage) {
Writer output = null;
File file = new File("src" + File.separator + sourcePackage + File.separator + fileNameWithExtension);
try {
output = new BufferedWriter(new FileWriter(file));
return (BufferedWriter) output;
} catch (IOException ex) {
Logger.getLogger(FileHelper.class.getName()).log(Level.SEVERE, null, ex);
return null;
}
}
Sadly, not the same way of getting the Readeras the Writer, but it works.
The key thing is that absolute paths always begin with a '/'.
Relative paths must not begin with a '/'. That's at least part of what's causing problems for you.
For the rest, you say "it doesn't work". But what doesn't work?

How to compile and run any file at any location in C,java and C++?

I am creating a editor kind of application where I want to compile and run (of course create, edit, open also) C,C++ and Java files;
I am creating it in Java.
Now for compilation and running I am taking the whole path of file
and compiling & running via this full path.
for eg.
compileFileCommand = javac /media/disk/eclipse/\/UniversalIDE/Java/FirstJava.java
try
{
System.out.println("Compiling Java File");
Process compileProcess = Runtime.getRuntime().exec(compileFileCommand);
compileProcess.waitFor();
String line = "";
BufferedReader bri = new BufferedReader(new InputStreamReader(compileProcess.getInputStream()));
BufferedReader bre = new BufferedReader(new InputStreamReader(compileProcess.getErrorStream()));
while ((line = bri.readLine()) != null)
{
System.out.println(line);
}
bri.close();
while ((line = bre.readLine()) != null)
{
System.out.println(line);
}
bre.close();
compileProcess.waitFor();
System.out.println("Done Java Compile.");
} catch (Exception e)
{
// TODO: handle exception
System.out.println("Exception in Java Compile. ");
System.out.println(e.getMessage());
}
Above code works fine and create a class file at location of java file.But bri.readLine() always contains null.
For running Java file
runFileCommand = java /media/disk/eclipse/\/UniversalIDE/Java/FirstJava
And for running C & CPP files the same procedure
For C compilation
String compileFileCommand = "gcc " + fileNameWithFullPath;
For C Running
String runFileCommand = "./" + fileNameWithFullPath.split(".c")[0];
For CPP compilation
String compileFileCommand = "g++ " + fileNameWithFullPath;
For CPP Running
String runFileCommand = "./" + fileNameWithFullPath.split(".cpp")[0];
I use the same code as used for compiling java file but it does not give anything as result and bri.readLine() gives null all the time.
Please help me to solve this problem and please give me any suggestion on my application.
The default output filename from gcc and g++ is a.out, not input filename without extension.
Try runFileCommand = "./a.out", or use the -o option with gcc/g++ to specify output filename.
Also none of the compilation commands output anything when there's no errors or warnings.
bri.readLine() returns null because when a Java file compiles without error, nothing is printed to standard out. Was that the question?

Running a Binary file using Java in Ubuntu

I am trying to run a binary file, which is Genia Sequence Splitter through java code. This Binary file is type x-executable and has no extension. I can run the file in terminal by using ./geniass arg1 arg2
where arg1 is input file arg2 is output file
I want to automate this process. I tried using this code
public class geniaSSTag {
public static void geniaSS(String inputFile){
System.out.println("Input file: "+inputFile);
String[]cmd={"bash","geniass/./geniass","in.txt","out.txt"};
try {
String errOutput="";
Process process = Runtime.getRuntime().exec(cmd);
String s = "";
BufferedReader br = new BufferedReader(new InputStreamReader(process
.getInputStream()));
while ((s = br.readLine()) != null)
{
s += s + "\n";
}
System.out.println(s);
BufferedReader br2 = new BufferedReader(new InputStreamReader(process.getErrorStream()));
while (br2.ready() && (s = br2.readLine()) != null)
{
errOutput += s;
}
System.out.println(errOutput);
} catch (IOException ex) {
Logger.getLogger(geniaSSTag.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
But I get this error when I try to run
geniass/./geniass: geniass/./geniass: cannot execute binary file
How can I solve this. Any help is appreciated.
Thank you
When you run the program, is the executable relative to the program's starting directory in the manner that it lies in "./genias/genias"? Note that the "/./" doesn't do anything except waste space, as it is shorthand for "the subdirectory that links back to the current directory".
Perhaps your "genias" executable isn't in a subdirectory named "genias", or the launching program is being launched from a different directory and can't find "genias/genias" relative to it's directory.
As suggested elsewhere, you can fix this by using an absolute path in the launching command. However, sometimes this just isn't flexible enough if you want multiple copies installed.
I would try first to run the command pwd from Java to see where you actually are. Then you can change the path to your executable accordingly. I guess using the path /home/xxx/yyy/geniass would always work.
Also there is a different version of Runtime.exec() which takes a working directory as an argument.
Try:
String[]cmd={"/full/path/to/geniass","in.txt","out.txt"};
Instead

Categories