I have made a program that scraps a website and extracts text and writes it in a .txt file. When I run my program from Intelij Idea every line is printed correctly in greek. But when I run the jar file from cmd the greek text is written as jibberish.
public class Logger extends Thread{
String input,path;
int matchNumber;
public Logger(String path0) {
path=path0;
}
public void log (int matchesNumber0,String input0) {
matchNumber=matchesNumber0;
input=input0;
this.run();
}
#Override
public void run() {
BufferedWriter textWriter = null;
DateFormat date = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Date today = Calendar.getInstance().getTime();
String stringDateToday = date.format(today);
if(input!=null) {
try {
String logFilePath = path;
textWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(logFilePath), StandardCharsets.UTF_8));
textWriter.write(stringDateToday + "-----" + matchNumber + "-----");
textWriter.write(input + "\n");
if (!input.contains(" content=")) {
setWarningMsg(input);
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("Incorrect Log File path!!!");
} finally {
try {
textWriter.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
cmd Output
It could be the case that the text-editor you are using to view the file may not be able to decode the greek-text file correctly.
If you are on Unix (or with Cygwin on Windows) the file program may be able to help. This program looks at the first few bytes to try and guess the program which opens your file aptly. or else trying opening the file in Intellij itself.
chcp 65001 && java -jar -Dfile.encoding=UTF-8 path/to/your/runnable/jar
That solved my problem!
I am using Netbeans on OS X and cannot seem to write text to a text file that I have in a package named "assets".
Below is the way I tried to accomplish writing to the text file and so far my method of doing this is not working.
The way I tried to approach this problem was converting a string to url, then converting the url to a uri. Then I used the uri for the new file parameter. After I tried to write a string using the class print writer.
public class Experiment {
File createFile(String path) {
java.net.URL url = getClass().getResource(path);
URI uri;
try {
uri = url.toURI();
}
catch (URISyntaxException e) {
uri = null;
}
if ((url != null) && (uri != null)) {
System.out.println("file loading sucess");
return new File(uri);
}
else {
System.out.println("Error file has not been loaded");
return null;
}
}
File file = createFile("/assets/myfile.txt");
public static void main(String[] args) {
Experiment testrun = new Experiment();
try {
PrintWriter writer = new PrintWriter(new FileWriter(testrun.file));
writer.println("it works");
writer.flush();
writer.close();
System.out.println("string was written");
}
catch (IOException e) {
System.out.println("there was an error while writing");
}
}
}
The output given from my try catch statements say that the file write code was executed.
file loading sucess
string was written
BUILD SUCCESSFUL (total time: 2 seconds)
I have also tried using absolute string paths for making a new file, but with null results. I am running out of ideas and hoping for some guidance or solution from somebody.
So I am still learning programming, I am creating a simple application that can backup a database but the problem is when I click the button for backup, nothing happens, it does not even display the "can't create backup". I am using xampp, in case that is relevant. I have zero idea as to why is it is not working, and I am really curios what is the reason behind it, any help will be greatly appreciated.
...
String path = null;
String filename;
//choose where to backup
private void jButtonLocationActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser fc = new JFileChooser();
fc.showOpenDialog(this);
String date = new SimpleDateFormat("MM-dd-yyy").format(new Date());
try {
File f = fc.getSelectedFile();
path = f.getAbsolutePath();
path = path.replace('\\', '/');
path = path+"_"+date+".sql";
jTextField1.setText(path);
} catch (Exception e) {
e.printStackTrace();
}
}
//backup
private void jButtonBackUpActionPerformed(java.awt.event.ActionEvent evt) {
Process p = null;
try{
Runtime runtime = Runtime.getRuntime();
p=runtime.exec("C:/xampp/mysq/bin/mysqldump -u root --add-drop-database -B capstone -r "+path);
int processComplete = p.waitFor();
if (processComplete==0) {
jLabel1.setText("Backup Created Success!");
} else {
jLabel1.setText("Can't create backup.");
}
} catch (Exception e) {
}
}
You use a try-catch block in the jButtonBackUpActionPerformed, but the catch statement is empty. Therefore, if an exception is raised for whatever reason, no file would be written and you would get no output. You can try to use e.printStackTrace() like in the catch statement of the other button for debugging.
I found the underlying problem, thanks to stan. It was a typo problem, instead of "mysql", I have put "mysq" thank you guys!
java.io.IOException: Cannot run program "C:/xampp/mysq/bin/mysqldump.exe": CreateProcess error=2, The system cannot find the file specified
this will run any shell script on Linux server. Test it on windows ... shoud work too
public static int executeExternalScript(String path) throws InterruptedException, IOException {
ProcessBuilder procBuilder = new ProcessBuilder(path);
procBuilder.redirectErrorStream(true);
Process process = procBuilder.start();
BufferedReader brStdout = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = null;
while((line = brStdout.readLine()) != null) { logger.info(line); }
int exitVal = process.waitFor();
brStdout.close();
return exitVal;}
I have this plugin that when installed, extracts some executables at some temporary location, and uses them. Here is my code:
public class StartCheck implements IStartup {
private BufferedReader buf=null;
public static String pathBandwidth;
public static String pathDeviceQuery;
public static String pathKernelLaunchOverhead;
public static String memoryLatency;
public void earlyStartup() {
// This method checks for presence of nvcc when Eclipse starts-up.
String command="nvcc --version";
Runtime run = Runtime.getRuntime();
Process pr;
try {
pr = run.exec(command);
pr.waitFor();
buf = new BufferedReader(new InputStreamReader(pr.getInputStream()));
//print-out the nvcc version
System.out.println(buf.readLine());
Preparation.return_val=true;
//extract the executables
Bundle bundle = Platform.getBundle("PTXAnalysis");
URL url_bandwidth = FileLocator.find(bundle, new Path("/Executables/bandWidth.out"), null);
URL url_deviceQuery = FileLocator.find(bundle, new Path("/Executables/deviceQuery.out"), null);
URL url_kernelLaunchOverhead = FileLocator.find(bundle, new Path("/Executables/empty"), null);
URL url_memoryLatency = FileLocator.find(bundle, new Path("/Executables/memLatency.out"), null);
try {
url_bandwidth = FileLocator.toFileURL(url_bandwidth);
url_deviceQuery = FileLocator.toFileURL(url_deviceQuery);
url_kernelLaunchOverhead = FileLocator.toFileURL(url_kernelLaunchOverhead);
url_memoryLatency = FileLocator.toFileURL(url_memoryLatency);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
pathBandwidth=url_bandwidth.toString();
pathDeviceQuery=url_deviceQuery.toString();
pathKernelLaunchOverhead=url_kernelLaunchOverhead.toString();
memoryLatency=url_memoryLatency.toString();
}catch (IOException e) {
//disable all commands since no further task can be done, prompt user to install nvcc.
System.out.println("nvcc was not found on this computer. You won't be able to use the energy estimation plug-in");
EnergyEstimator.return_val=false;
Preparation.return_val=false;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
When I install the plugin, it gives me this location (one of the many), where the executable has been extracted:
/home/limafoxtrottango/.eclipse/org.eclipse.platform_4.4.1_2069420271_linux_gtx_x86_64/configuration/org.eclipse.osgi/460/0/.cp/Executables/bandWidth.out
Now, the problems: I can't find any such directory. I understand that it is a temporary directory, but it does not show-up even if Eclipse is running. I am using one of these paths to run an executable using ProcessBuilder. Here is the code:
public static void runExecutable(){
initializeArray();
path_result="/home/"+System.getProperty("user.name")+"/kernelLaunchOverhead.txt";
String path_executable=StartCheck.pathKernelLaunchOverhead.substring(path_result.indexOf('/'),path_result.lastIndexOf('/')+1); //path to the directory in which the executable is extracted
try {
fw = new FileWriter(path_result);
for(int i=0;i<arr.length;i++){
ProcessBuilder builder=new ProcessBuilder("./empty",Integer.toString(arr[i]));
builder.directory(new File(path_executable));
int av=0;
float sum=0;
while(av<10){
Process pr=builder.start();
stdin = pr.getInputStream();
isr = new InputStreamReader(stdin);
br = new BufferedReader(isr);
sum=sum+Float.parseFloat(line=br.readLine());
av++;
}
fw.write(arr[i]+" "+Float.toString(sum/10));
fw.write("\n");
}
fw.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
FillArrays(path_result);
BestLineFit();
saveModel("/home/"+System.getProperty("user.name")+"/KernelLaunchOverheadModel.txt");
}
On invoking this function, nothing happens. It does not even throw any FileNotFound exceptions. Normally, it should have found the executable in the directory, and run it. But after installing the plugin, nothing happens.
To re-iterate, the class StartCheck is successfully showing to me the path to which the executables have been extracted. But those paths do not exist anywhere on my system.
Directories starting with . (such as the .eclipse in the path you show) are hidden on Linux and macOS systems.
You can see them from the command line using ls -a
I want to create diff of two files. I tried searching for code in Java that does it, but didnt find any simple code/ utility code for this. Hence, I thought if I can somehow run linux diff/sdiff command from my java code and make it return a file that stores the diff then it would be great.
Suppose there are two files fileA and fileB. I should be able to store their diff in a file called fileDiff through my java code. Then fetching data from fileDiff would be no big deal.
You can use java.lang.Runtime.exec to run simple code. This gives you back a Process and you can read its standard output directly without having to temporarily store the output on disk.
For example, here's a complete program that will showcase how to do it:
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class testprog {
public static void main(String args[]) {
String s;
Process p;
try {
p = Runtime.getRuntime().exec("ls -aF");
BufferedReader br = new BufferedReader(
new InputStreamReader(p.getInputStream()));
while ((s = br.readLine()) != null)
System.out.println("line: " + s);
p.waitFor();
System.out.println ("exit: " + p.exitValue());
p.destroy();
} catch (Exception e) {}
}
}
When compiled and run, it outputs:
line: ./
line: ../
line: .classpath*
line: .project*
line: bin/
line: src/
exit: 0
as expected.
You can also get the error stream for the process standard error, and output stream for the process standard input, confusingly enough. In this context, the input and output are reversed since it's input from the process to this one (i.e., the standard output of the process).
If you want to merge the process standard output and error from Java (as opposed to using 2>&1 in the actual command), you should look into ProcessBuilder.
You can also write a shell script file and invoke that file from the java code. as shown below
{
Process proc = Runtime.getRuntime().exec("./your_script.sh");
proc.waitFor();
}
Write the linux commands in the script file, once the execution is over you can read the diff file in Java.
The advantage with this approach is you can change the commands with out changing java code.
You need not store the diff in a 3rd file and then read from in. Instead you make use of the Runtime.exec
Process p = Runtime.getRuntime().exec("diff fileA fileB");
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
try to use unix4j. it s about a library in java to run linux command. for instance if you got a command like:
cat test.txt | grep "Tuesday" | sed "s/kilogram/kg/g" | sort
in this program will become:
Unix4j.cat("test.txt").grep("Tuesday").sed("s/kilogram/kg/g").sort();
You can call run-time commands from java for both Windows and Linux.
import java.io.*;
public class Test{
public static void main(String[] args)
{
try
{
Process process = Runtime.getRuntime().exec("pwd"); // for Linux
//Process process = Runtime.getRuntime().exec("cmd /c dir"); //for Windows
process.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line=reader.readLine())!=null)
{
System.out.println(line);
}
}
catch(Exception e)
{
System.out.println(e);
}
finally
{
process.destroy();
}
}
}
Hope it Helps.. :)
Runtime run = Runtime.getRuntime();
//The best possible I found is to construct a command which you want to execute
//as a string and use that in exec. If the batch file takes command line arguments
//the command can be constructed a array of strings and pass the array as input to
//the exec method. The command can also be passed externally as input to the method.
Process p = null;
String cmd = "ls";
try {
p = run.exec(cmd);
p.getErrorStream();
p.waitFor();
}
catch (IOException e) {
e.printStackTrace();
System.out.println("ERROR.RUNNING.CMD");
}finally{
p.destroy();
}
The suggested solutions could be optimized using commons.io, handling the error stream, and using Exceptions. I would suggest to wrap like this for use in Java 8 or later:
public static List<String> execute(final String command) throws ExecutionFailedException, InterruptedException, IOException {
try {
return execute(command, 0, null, false);
} catch (ExecutionTimeoutException e) { return null; } /* Impossible case! */
}
public static List<String> execute(final String command, final long timeout, final TimeUnit timeUnit) throws ExecutionFailedException, ExecutionTimeoutException, InterruptedException, IOException {
return execute(command, 0, null, true);
}
public static List<String> execute(final String command, final long timeout, final TimeUnit timeUnit, boolean destroyOnTimeout) throws ExecutionFailedException, ExecutionTimeoutException, InterruptedException, IOException {
Process process = new ProcessBuilder().command("bash", "-c", command).start();
if(timeUnit != null) {
if(process.waitFor(timeout, timeUnit)) {
if(process.exitValue() == 0) {
return IOUtils.readLines(process.getInputStream(), StandardCharsets.UTF_8);
} else {
throw new ExecutionFailedException("Execution failed: " + command, process.exitValue(), IOUtils.readLines(process.getInputStream(), StandardCharsets.UTF_8));
}
} else {
if(destroyOnTimeout) process.destroy();
throw new ExecutionTimeoutException("Execution timed out: " + command);
}
} else {
if(process.waitFor() == 0) {
return IOUtils.readLines(process.getInputStream(), StandardCharsets.UTF_8);
} else {
throw new ExecutionFailedException("Execution failed: " + command, process.exitValue(), IOUtils.readLines(process.getInputStream(), StandardCharsets.UTF_8));
}
}
}
public static class ExecutionFailedException extends Exception {
private static final long serialVersionUID = 1951044996696304510L;
private final int exitCode;
private final List<String> errorOutput;
public ExecutionFailedException(final String message, final int exitCode, final List<String> errorOutput) {
super(message);
this.exitCode = exitCode;
this.errorOutput = errorOutput;
}
public int getExitCode() {
return this.exitCode;
}
public List<String> getErrorOutput() {
return this.errorOutput;
}
}
public static class ExecutionTimeoutException extends Exception {
private static final long serialVersionUID = 4428595769718054862L;
public ExecutionTimeoutException(final String message) {
super(message);
}
}
if the opening in windows
try {
//chm file address
String chmFile = System.getProperty("user.dir") + "/chm/sample.chm";
Desktop.getDesktop().open(new File(chmFile));
} catch (IOException ex) {
Logger.getLogger(Frame.class.getName()).log(Level.SEVERE, null, ex);
{
JOptionPane.showMessageDialog(null, "Terjadi Kesalahan", "Error", JOptionPane.WARNING_MESSAGE);
}
}
ProcessBuilder processBuilder = new ProcessBuilder();
// -- Linux --
// Run a shell command
processBuilder.command("bash", "-c", "ls /home/kk/");
// Run a shell script
//processBuilder.command("path/to/hello.sh");
// -- Windows --
// Run a command
//processBuilder.command("cmd.exe", "/c", "dir C:\\Users\\kk");
// Run a bat file
//processBuilder.command("C:\\Users\\kk\\hello.bat");
try {
Process process = processBuilder.start();
StringBuilder output = new StringBuilder();
BufferedReader reader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
output.append(line + "\n");
}
int exitVal = process.waitFor();
if (exitVal == 0) {
System.out.println("Success!");
System.out.println(output);
System.exit(0);
} else {
//abnormal...
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}