How to display Greek Character when running from cmd - java

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!

Related

Unable to concat mp4 files using ffmpeg

I am using ffmpeg to combine two mp4 files without including their audio; however, despite following the formatting in many other posts, I'm unable to get my code to function.
//public variables
public void test(){
String canonicalPath = new File(".").getCanonicalPath();
String ffmpegPath="/usr/bin/local/ffmpeg";
String vidSectPath=canonicalPath.concat("/src/Video-Sections");
String vidPath=canonicalPath.concat("/src/Videos");
String tempA=vidSectPath+"/Earth.mp4";
String tempB=vidSectPath+"/Waves.mp4";
String tempVidPath=vidPath+"/tvp.mp4";
String[]cmd1={ffmpegPath,"-i",tempA,"-i",tempB,"-filter_complex","[0:0][1:0]concat=n=2:v=1:a=0[out]","-map","[out]",tempVidPath};
ProcessBuilder pb = new ProcessBuilder(cmd1);
boolean exeCmdStatus = executeCMD(pb);
}
private boolean executeCMD(ProcessBuilder pb)
{
pb.redirectErrorStream(true);
Process p = null;
try {
p = pb.start();
} catch (Exception ex) {
ex.printStackTrace();
System.out.println("oops");
p.destroy();
return false;
}
// wait until the process is done
try {
p.waitFor();
} catch (InterruptedException e) {
e.printStackTrace();
System.out.println("woopsy");
p.destroy();
return false;
}
return true;
}
I get a new mp4 file after running this code, but the mp4 file has 0 bytes and can't be opened in any media player. I've tried adding "-pix_fmt yuv420p" to cmd1, but this doesn't seem to help in any way.
I've also tried using the concat demuxer method by making the cmd1 string[] variable equal to:
ffmpegPath,"-f","concat","-i","-safe","0","/Users/JL/Documents/workspace/VidTest/src/concat.txt","-vcodec","copy",tempVidPath};
In which the content of concat.txt is
file '/Users/JL/Documents/workspace/VidTest/src/Video-Sections/Earth.mp4'
file '/Users/JL/Documents/workspace/VidTest/src/Video-Sections/MovWaves.mp4'
However, this method doesn't seem to be able to create the concatenated mp4 file.
I'm not sure what is wrong with my code. I'm also using a mac to execute the code.

Saving input to a file is replaced when re-running

I'm trying to create something similar to a mail server.
Now, I'm supposed to have a file called 'Credentials' that saves the email and password entered each time I run the client.
File Credentials = new File("Server\\Credentials.txt");
try{
if(Credentials.createNewFile()){
System.out.println("Credentials created");
}else {System.out.println("Credentials already exists");}
}catch(Exception error){}
try (
PrintWriter out = new PrintWriter(Credentials, "UTF-8")
) {
out.println("Email: " + email);
out.println("Password: " + password);
} catch(IOException e) {
e.printStackTrace();
}
However, each time a client runs, it replaces the old email and password. Any idea how to make it continue to the next line without replacing? Thank you.
As previously mentioned you have to use the correct constructor, which will append your text instead of overriding.
But I would suggest to do it this way:
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
doSomething("test" + i);
}
}
static void doSomething(String text) {
try (PrintWriter test = new PrintWriter(new BufferedWriter(new FileWriter("your path", true)))) {
test.print(text);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Here are some further informations and different approaches for your issue:
How to append text to an existing file in Java?

How to run a docker image from java Program?

I'm trying to run an Ubuntu image from a java program using a script; here is how:
my java code:
public static void main(String[] args) {
executeCommand("/home/abrahem/IdeaProjects/untitled3/src/createContainer.sh");
}
public static void executeCommand(String filePath) {
File file = new File(filePath);
if (!file.isFile()) {
throw new IllegalArgumentException("The file " + filePath + " does not exist");
}
try {
if (isLinux()) {
Process p = Runtime.getRuntime().exec("sh " + filePath);
p.waitFor(); // i tried to remove this but still not work for my me
} else if (isWindows()) {
Runtime.getRuntime().exec("cmd /c start " + filePath);
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
here is my createContainer.sh script file:
#!bin/sh
sudo docker run ubuntu
when I go to bin and type:
docker ps
or
docker ps -a
It should show the running Ubuntu container, but it doesn't.
Note: there is nothing wrong with the shell location; I try to create file in shell file and it works.
You do not capture any error messages or normal output from your process. Maybe it just works?
Use getErrorStream() and getOutputStream() methods of Process to capture the output from the process somewhat like described here. You may just see the expected output. If not, it should be the error message on the error stream.

Backup a mysql [xampp] database in java

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;}

Is it possible to execute a Java code string at runtime in Android?

I want to get a line of Java code from user and execute it in Android. For example:
String strExecutable = " int var; var = 4 + 3"
Object obj = aLibrary.eval(strExecutable);
It is not java script and I want to run a java code.
Is it possible? If yes how?
I have studied links like this. But they are questions about JVM not Android Dalvik.
You can try BeanShell! It's super easy and works also on android. Just build your app with jar library.
import bsh.Interpreter;
private void runString(String code){
Interpreter interpreter = new Interpreter();
try {
interpreter.set("context", this);//set any variable, you can refer to it directly from string
interpreter.eval(code);//execute code
}
catch (Exception e){//handle exception
e.printStackTrace();
}
}
But be careful! Using this in production app may be security risk,
especially if your app interacts with users data / files.
You can try something like this:
// Code Execute, Khaled A Khunaifer, 27 March 2013
class CodeExcute
{
public static void execute (String[] commands, String[] headers)
{
// build commands into new java file
try
{
FileWriter fstream = new FileWriter("Example.java");
BufferedWriter out = new BufferedWriter(fstream);
out.write("");
for (String header : headers) out.append(header);
out.append("class Example { public static void main(String args[]) { ");
for (String cmd : commands) out.append(cmd);
out.append(" } }");
out.close();
}
catch (Exception e)
{
System.err.println("Error: " + e.getMessage());
}
// set path, compile, & run
try
{
Process tr = Runtime.getRuntime().exec(
new String[]{ "java -cp .",
"javac Example.java",
"java Example" } );
}
catch (Exception e)
{
System.err.println("Error: " + e.getMessage());
}
}
}

Categories