I want to create an java program to compress an css file using YUI
I am new learner in java.
My Code is:
import java.io.BufferedInputStream;
import java.io.IOException;
public class Run extends Object
{
public static void main(String args[]) throws IOException, InterruptedException
{
System.out.println("Calling jar");
Process p = Runtime.getRuntime().exec("java -Xmx32m -jar yui.jar in.css");
BufferedInputStream bis = new BufferedInputStream(p.getInputStream());
synchronized(p)
{
p.waitFor();
}
System.out.println(p.exitValue());
int b = 0;
while((b = bis.read()) > 0)
{
System.out.print((char)b);
}
System.out.println("Called jar");
}
}
I took reference from here.
the command:
java -Xmx32m -jar yui.jar in.css
works fine in cmd but I get no output when I run above program
the output I get for above is:
Calling jar
1
Called jar
Please tell Me what I am doing wrong or what is the right way of doing this.
You are getting the "1" because there is nothing to read in the stream.
I'm guessing that you're trying to run the file from Eclipse or some other IDE. If so, you need to place your yui.jar and in.css files to same directory relative to where your Run class is.
If you're using default run configurations, you'll just want to put the files into the root directory of your eclipse project. For example, this works for me:
Test
src
com
test
Run.java
yui.jar
in.css
A better way to handle your situation is to use absolute or relative paths instead of just specifiying yui.jar or in.css. Create two variables for the two relative paths and then create the command string.
Related
I'm new to IntelliJ. I'm running into problems on running very basic File I/O programs.
import java.io.*;
import java.util.Scanner;
public class NamePlaces {
public static void main(String[] args) throws FileNotFoundException{
String nameTxt = args[0];
String placeTxt = args[1];
Scanner nameScanner = null;
Scanner placeScanner = null;
try{
FileReader names = new FileReader(nameTxt);
FileReader places = new FileReader(placeTxt);
nameScanner = new Scanner(new BufferedReader(names));
placeScanner = new Scanner(new BufferedReader(places));
while(nameScanner.hasNext() && placeScanner.hasNext()){
System.out.format("%s lives in %s \n",nameScanner.next(),placeScanner.next());
}
}finally {
if (nameScanner != null){
nameScanner.close();
}
if (placeScanner != null){
placeScanner.close();
}
}
}
here's my project structure
and here's my output
/usr/lib64/jvm/java/bin/java -javaagent:/home/abhishek/intellij/lib/idea_rt.jar=42185:/home/abhishek/intellij/bin -Dfile.encoding=UTF-8 -classpath /home/abhishek/Documents/code/ideaprojects/files/out/production/files NamePlaces names.txt places.txt
Exception in thread "main" java.io.FileNotFoundException: names.txt (No such file or directory)
at java.base/java.io.FileInputStream.open(FileInputStream.java:219)
at java.base/java.io.FileInputStream.<init>(FileInputStream.java:157)
at java.base/java.io.FileInputStream.<init>(FileInputStream.java:112)
at java.base/java.io.FileReader.<init>(FileReader.java:60)
at NamePlaces.main(NamePlaces.java:12)
Process finished with exit code 1
So I've been wrestling with this problem for quite some time now. I do not understand why it won't read the file names.txt when it is available in the src folder as well as the out/production/files folder too. What am I missing. I've tried changing directories, classpath seems right too. I'm out of options here. Any help is appreciated. thanks.
In Java if you are not using class.getResource() it will be looking in the project/surrounding folder. If you compiled the .class file by hand it would work in its current state. But to fix the issue moving names.txt and places.txt to the files project folder will fix it.
I am able to run the program. I however could not figure out a simpler way than this.
So I changed my code by adding
import java.nio.file.Path;
import java.nio.file.Paths;
to the imports.
And inside the main(), I added the following statement to get the path.
Path path = Paths.get('path/to/directory/');
And then I used this path to hard code the path into the call to the FileReader such as
FileReader names = new FileReader(path.toString()+"/"+namesTxt);
This got the program running. I know this is not the optimum or the desired solution but at the moment, I wanted the program to run.
I will update the answer once I learn more about how the IntelliJ works in identifying files because hard coding paths is not a good software design practice.
This Java programm opens a Batch file and passes the string folderName
public class FolderCreator {
public static void main(String[] args) {
try{
Process p = Runtime.getRuntime().exec("C:/Documents/NameFolder.bat folderName");
p.waitFor();
}catch(Exception e) {
System.out.println(e);
}
}
}
This is the NameFolder.bat file. It shall create a folder with the name from the passed Java variable above.
//What do I need to ad here?
if not exist "C:\Desktop\folderName\" mkdir C:\Desktop\folderName
What do I need to add to the Batch file?
EDIT:
This works
if not exist "C:\Desktop\%1\" mkdir C:\Desktop\%1
Batch Script
The following will create a directory only if that directory does not exist
if not exist "C:\Users\%USERNAME%\Desktop\%1" (
mkdir "C:\Users\%USERNAME%\Desktop\%1"
)
Assuming you save this to file C:/Documents/NameFolder.bat you just execute it with the same exact Java code
Process p = Runtime.getRuntime().exec("C:/Documents/NameFolder.bat folderName");
This will create a c:\Users\%USERNAME%\Desktop\folderName directory only if that directory doesn't already exist.
This is not best practice. Please read up on executing shell/batch scripts from Java
I have a Jenkins job running. I just want to get all files. In every file name there is a Chinese letter. So the problem is now that Jenkins has problems reading in those files. Jenkins makes just "?" out of the Asian letter. The second problem is. Actually it is more than 100 files. But Jenkins only gives me 20 files. Maybe now a lot of files will look the same because of the question mark "?" .
Does anyone know how I can fix this. The problem only occurs on Jenkins ( running on Linux ) . On my local machine in Eclipse it works though.
File resourcePath = new File("resources/china_data/");
File[] files = resourcePath.listFiles();
for (final File file : files)
{
System.out.console(file.getName);
}
An alternative solution is to use the new java.nio.Path api in place of the java.io.File api
Also try setting the below in your code initially.
System.setProperty("sun.jnu.encoding","utf-8");
System.setProperty("file.encoding","UTF-8");
Assuming you are using System.out.println, this happens when the program runs with an ASCII locale:
$ cat Main.java
import java.util.*;
import java.io.*;
class Main {
public static void main(String[] args) throws Exception {
File resourcePath = new File("resources/china_data/");
File[] files = resourcePath.listFiles();
for (final File file : files)
{
System.out.println(file.getName());
}
}
}
$ javac Main.java
$ LC_CTYPE=C java Main
???????
When the program runs with a UTF-8 capable locale, either from the environment or configured through Java, you get the expected result:
$ LC_CTYPE=en_US.UTF-8 java Main
中华人民共和国
$ LC_CTYPE=C java -Dfile.encoding=UTF-8 Main
中华人民共和国
If you're not sure how to configure your server, you can also do this from within Java:
System.setOut(new PrintStream(System.out, true, "UTF-8"));
I am learning basic I/O for java, and the following example is from Oracle's tutorial. The program flows a FileNotFound exception. I place the file under the working directory, and I also tried to use absolute file path, and the result is still the same. I use Eclipse to write the code. What could be causing this exception? Thanks
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class CopyBytes {
public static void main(String[] args) throws IOException {
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream("xanadu.txt");
out = new FileOutputStream("outagain.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
} finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
There are a lot of things that can cause that exception. Here are a few things to try:
-Verify that Xanadu.txt is a file using the isFile() method. If it returns false then you know where your problem is.
-Try placing the file in the project directory.
-Given that you already tried using the absolute file path I would also make sure that your program has permission to look at and write to the file. To check if eclipse has permission go to the properties of your file
Place the file xanadu.txt in the project directory and FileNotFoundException will go away.
FileInputStream will expect an existing input file.
The code probably isn't being executed from the path you expected.
You should use the home folder for this. C:\Users\<User Name> on windows and /home/<User Name> on linux. You can create a folder there to put your files.
To get the home directory, you can use this.
System.getProperty("user.dir")
Other solution would be to pack the files inside the JAR.
If you want to debug your problem, you can get the current directory like this.
<Your Class>.class.getProtectionDomain().getCodeSource().getLocation()
I have created a java program in eclipse and I am now ready to export it as a jar. My program uses an image file and an executable file. When testing my program in eclipse I referred to these file with a full path, which I obviously cannot do for the jar. Therefore, I changed them like this:
public static final String DRIVERLOC = "./resources/IEDriverServer.exe";
//some other code
File file = new File(DRIVERLOC);
System.setProperty("webdriver.ie.driver", file.getAbsolutePath());
and
File pic = new File("./images/Open16.gif");
openButton = new JButton("Select the Text File", createImageIcon(pic.getAbsolutePath()));
I put the images and the resources and images directory in the same directory with the jar. Now for some reason when I run the jar the IEDriverServer works fine but the image does not work and the error is that it cannot find the image. I am confused since I cannot seems to tell the difference. I also used "images/Open16.gif" which did not work either. Why would one work but the other does not? What is the easiest way to fix this?
We do this exact same thing with Selenium Drivers.
What you need to do is take the executable file out of the jar and put it some where windows can run it. If you try and open a jar/zip in Windows Explorer and then double click the .exe inside of a jar/zip, windows will extract the file to a temp directory, and then run it. So do the same thing:
import org.apache.commons.io.IOUtils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class TestClass {
public static void main (String[] args) throws IOException {
InputStream exeInputStream = TestClass.class.getClassLoader().getResourceAsStream("resources/IEDriverServer.exe");
File tempFile = new File("./temp/IEDriverServer.exe");
OutputStream exeOutputStream = new FileOutputStream(tempFile);
IOUtils.copy(exeInputStream, exeOutputStream);
// ./temp/IEDriverServer.exe will be a usable file now.
System.setProperty("webdriver.ie.driver", tempFile.getAbsolutePath());
}
}
Let's say you save the jar and make it run this main function by default.
Running C:\code\> java -jar TestClass.jar Will run the jar from the C:\code directory. It will create the executable at C:\code\temp\IEDriverServer.exe
With your path set to "./resources/IEDriverServer.exe" you are referring to a file on the hard drive "." which does not exist.
You need to get the path of your .jar-file.
You can do this by using
System.getProperty("java.class.path")
This can return multiple values, seperated by semi-colons. The first one should be the folder your jar is in.
You can also use
<AnyClass>.class.getProtectionDomain().getCodeSource().getLocation()
I hope this helps :)
EDIT:
// First, retrieve the java.class.path property. It returns the location of all jars /
// folders (the one that contains your jar and the location of all dependencies)
// In my test it returend a string with several locations split by a semi-colon, so we
// split it and only take the first argument
String jarLocation = System.getProperty("java.class.path").split(";")[0];
// Then we want to add that path to your ressource location
public static final String DRIVERLOC = jarLocation + "/resources/IEDriverServer.exe";
//some other code
File file = new File(DRIVERLOC);
System.setProperty("webdriver.ie.driver", file.getAbsolutePath());
You can read about this here.