While trying to write file in specified directory i am getting exception.
Java code :-
public void jsonToYaml(JSONObject json, String studioName)
throws JSONException, org.codehaus.jettison.json.JSONException,
IOException {
Yaml.dump(Yaml.dump(JsonToMap.jsonToMap(json)), new File("config.yml"));
BufferedReader br = new BufferedReader(new FileReader("config.yml"));
String line;
studioName = studioName.toLowerCase();
File writeFile = new File("sudo /var/iprotecs/idns2.0","" + studioName + ".yaml");
FileOutputStream fos = new FileOutputStream(writeFile);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
try {
while ((line = br.readLine()) != null) {
String line1 = line.replace("\"", "");
String line2 = line1.replaceAll("!java.util.HashMap", "");
String line3 = line2.replaceAll("---", "");
String line4 = line3.replace("|", "");
System.out.println(line4);
bw.write(line4);
bw.newLine();
}
} catch (FileNotFoundException e) {
System.out.println(e);
}
}
Exception :-
How to create file write content to it.
java.io.FileNotFoundException: sudo /var/iprotecs/idns2.0/asia.yaml (No such file or directory)
Do not name the file sudo var/... but only /var/.... sudo is a shell command.
sudo is not a file you want to write to, It is a program that is used to temporarily elevate privileges. I think you need something like:
File writeFile = new File("/var/iprotecs/idns2.0", studioName + ".yaml");
You cannot write outside of the /home/ directory by default.
Also sudo is a command, you cannot execute a command from a BufferedWriter.
So, launch your jar with sudo java -jar yourJar.jar or launch your IDE in root (for eclipse sudo eclipse).
And try something like that:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
class jsonToYaml
{
public static void main(String args[]) throws Exception
{
String line, allLine;
StringBuilder stringBuilder = new StringBuilder();
BufferedReader bufferedReader = new BufferedReader(new FileReader("config.yml")); // Add config.yml into the BufferedReader
try
{
while ((line = bufferedReader.readLine()) != null) // Read line per line config.yml (from the BufferedReader) until it is over
{
stringBuilder.append(line); // add the line into stringBuilder
stringBuilder.append(System.lineSeparator()); // add a lineSeparator into stringBuilder
}
allLine = stringBuilder.toString(); // allLine is equal to stringBuilder
}
finally
{
bufferedReader.close(); // Close the BufferedReader
}
String studioName = System.getProperty("user.name"); // set studioName
FileWriter fileWriter = new FileWriter("/var/iprotecs/idns2.0/" + studioName + ".yaml", true); // create a FileWriter && true for append a String into your FileWriter or false for ecrase a String into your FileWriter
try
{
fileWriter.write(allLine ,0, allLine.length()); // Write allLine into "/var/iprotecs/idns2.0/ + studioName + .yaml"
}
finally
{
fileWriter.close(); // close the FileWriter
}
}
}
You need to launch Eclipse in sudo mode from your terminal.
It is always the same if you need to write a file outside of /home or /media.
Related
I am running the following code. I ask the user to enter a Java program. The user's program will compile correctly, and if there is any error it will be pointed out. But when I try to run the program it won't run at all. Instead I get this message:
Program finished with exit code 0.
How do I solve this problem?
import java.io.*;
import java.util.*;
public class myprog1 {
public static void main(String [] args) throws IOException, InterruptedException {
System.out.println("enter the candidate name");
Scanner scan = new Scanner(System.in);
String cname = scan.next();
String cfilename = "candidate.java";
String file1 = "/home/prakasha/IdeaProjects/" + cname;
String file2 = "/home/prakasha/IdeaProjects/";
File file = new File("/home/prakasha/IdeaProjects/" + cname);
file.mkdir();
if (!file.exists()) {
System.out.println("filenotfound");
} else {
System.out.println("the code is stored in his dir :" + cname);
File fobj = new File(file, "/" + cfilename);
FileWriter fw = new FileWriter(fobj);
System.out.println("enter the code");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String code = br.readLine();
fw.append(code);
System.out.println(fobj);
fw.close();
ProcessBuilder pb = new ProcessBuilder
("javac", file1 + "/" + cfilename);
pb.inheritIO();
Process process = pb.start();
process.waitFor();
BufferedReader is =
new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
// reading the output
while ((line = is.readLine()) != null)
System.out.println(line);
ProcessBuilder pb1 = new ProcessBuilder
("java", file1 + "/" + "candidate");
System.out.println(file1 + "/" + "candidate");
pb.inheritIO();
Process process1 = pb1.start();
BufferedReader reading =
new BufferedReader(new InputStreamReader(process1.getInputStream()));
String line1;
while ((line1 = reading.readLine()) != null)
System.out.println(line1);
}
}
}
The argument to the java command is a class name.
/home/prakasha/IdeaProjects/XXX/candidate is not a class name, since / is not a valid character in a class name.
Two ways to fix the problem:
Specify location using -cp argument.
Change the working directory to the folder where the files are.
Also, since you use inheritIO(), there is no output to copy, so getInputStream() is a null input stream.
I'd suggest using the second fix:
new ProcessBuilder("javac", "candidate.java")
.directory(file)
.inheritIO()
.start()
.waitFor();
new ProcessBuilder("java", "candidate")
.directory(file)
.inheritIO()
.start()
.waitFor();
I have to execute two commands in terminal from my java program. Here is the java code that I am using :
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Runterminal {
public static void main(String[] args) {
Process proc;
Process procRun;
String compileCommand = "aarch64-linux-g++ -std=c++14 hello.cpp";
String runCommand = "aarch64-linux-objdump -d a.out";
try{
proc = Runtime.getRuntime().exec(compileCommand);
procRun = Runtime.getRuntime().exec(runCommand);
// Read the output
BufferedReader reader =
new BufferedReader(new InputStreamReader(proc.getInputStream()));
String line = "";
while((line = reader.readLine()) != null) {
System.out.print(line + "\n");
}
proc.waitFor();
BufferedReader readero =
new BufferedReader(new InputStreamReader(procRun.getInputStream()));
String lineo = "";
while((lineo = readero.readLine()) != null) {
System.out.print(lineo + "\n");
}
procRun.waitFor();
}
catch(Exception e)
{
System.out.println("Exception occurred "+e);
}
}
}
My hello.cpp file is stored in the home directory. When I compile the java program it gets compiled but while running it it is throwing exception. Here's the output which I am getting :
Exception occurred java.io.IOException: Cannot run program "aarch64-
linux-g++": error=2, No such file or directory
Try to replace using following lines in your code,
String compileCommand = "g++ -std=c++14 hello.cpp";
String runCommand = "./a.out";
And keep the .cpp file in same directory where the .class file lies.
The following code snippet i had given is using exec function and executes hello program (simple "hello world" printing java program). But as soon as i execute the main program, print statement of instream.readline() simply returns NULL. Please try to sort out the problem. Hope the explanation is clear.
CODE:
Process process2=null;
BufferedReader inStream=null;
try
{
process2 = Runtime.getRuntime().exec("java hello");
}
catch(IOException e1)
{
System.err.println("Error on exec method");
e1.printStackTrace();
}
try
{
inStream = new BufferedReader(new InputStreamReader(process2.getInputStream() ));
System.out.println(inStream.readLine());
}
catch(IOException e1)
{
System.err.println("Error on inStream.readLine()");
e1.printStackTrace();
}
First of all your hello.java should be already compiled n the class file should present in the current directory where the program is located.
And for getting errors, you can get error stream from process class's object.
BufferedReader stdError = new BufferedReader(new InputStreamReader(pr.getErrorStream()));
String s="";
while ((s = stdError.readLine()) != null)
System.out.println(s);
Working with Eclipse/java7/windows
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class ProcessDemo {
public static void main(String[] args) throws Exception {
final String dir = System.getProperty("user.dir");
System.out.println("current dir = " + dir);
Runtime run = Runtime.getRuntime();
Process pr=run.exec("javac -d "+ dir +"\\src "+ dir+"\\src\\HelloDemo.java");
pr.waitFor();
BufferedReader stdError = new BufferedReader(new InputStreamReader(pr.getErrorStream()));
BufferedReader buf = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String line = "";
String s;
// read any errors from the attempted command
System.out.println("Here is the standard error of the command (if any):\n");
while ((s = stdError.readLine()) != null)
System.out.println(s);
//read output
while ((line=buf.readLine()) != null)
System.out.println(line);
pr.destroy();
Runtime run1 = Runtime.getRuntime();
Process pr1=run1.exec("java -cp "+dir+"\\src HelloDemo");
BufferedReader stdError1 = new BufferedReader(new InputStreamReader(pr1.getErrorStream()));
BufferedReader buf1 = new BufferedReader(new InputStreamReader(pr1.getInputStream()));
//interpretting file n executing it line by line :D :P
pr1.waitFor();
String temp;
// read any errors from the attempted command
System.out.println("\n\nHere is the standard error of the command (if any):\n");
while ((temp = stdError1.readLine()) != null)
System.out.println(temp);
//read output
System.out.println(buf1.readLine());
while ((temp=buf1.readLine()) != null)
System.out.println(temp);
}
}
public static void main(String[] args) {
ArrayList<String> studentTokens = new ArrayList<String>();
ArrayList<String> studentIds = new ArrayList<String>();
try {
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream(new File("file1.txt"));
BufferedReader br = new BufferedReader(new InputStreamReader(fstream, "UTF8"));
String strLine;
// Read File Line By Line
while ((strLine = br.readLine()) != null) {
strLine = strLine.trim();
if ((strLine.length()!=0) && (!strLine.contains("#"))) {
String[] students = strLine.split("\\s+");
studentTokens.add(students[TOKEN_COLUMN]);
studentIds.add(students[STUDENT_ID_COLUMN]);
}
}
for (int i=0; i<studentIds.size();i++) {
File file = new File("query.txt"); // The path of the textfile that will be converted to csv for upload
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = "", oldtext = "";
while ((line = reader.readLine()) != null) {
oldtext += line + "\r\n";
}
reader.close();
String newtext = oldtext.replace("sanid", studentIds.get(i)).replace("salabel",studentTokens.get(i)); // Here the name "sanket" will be replaced by the current time stamp
FileWriter writer = new FileWriter("final.txt",true);
writer.write(newtext);
writer.close();
}
fstream.close();
br.close();
System.out.println("Done!!");
} catch (Exception e) {
e.printStackTrace();
System.err.println("Error: " + e.getMessage());
}
}
The above code of mine reads data from a text file and query is a file that has a query in which 2 places "sanid" and "salabel" are replaced by the content of string array and writes another file final . But when i run the code the the final does not have the queries. but while debugging it shows that all the values are replaced properly.
but while debugging it shows that all the values are replaced properly
If the values are found to be replaced when you debugged the code, but they are missing in the file, I would suggest that you flush the output stream. You are closing the FileWriter without calling flush(). The close() method delegates its call to the underlying StreamEncoder which does not flush the stream either.
public void close() throws IOException {
se.close();
}
Try this
writer.flush();
writer.close();
That should do it.
I have this piece of code
package Classes;
import java.io.*;
public class IpAdministrator {
public Boolean isActive(String ipAddress) {
boolean isActive = false;
String cmd;
String OS = System.getProperty("os.name");
System.out.println(OS);
String tmpfolder = System.getProperty("java.io.tmpdir");
System.out.println(tmpfolder);
//iptmp.deleteOnExit();
if (OS.equals("Linux")) {
cmd = "ping " + ipAddress + " -c 1";
} else {
cmd = "cmd /c ping " + ipAddress + " -n 1";
}
try {
String s = null;
Process p = Runtime.getRuntime().exec(cmd);
File iptmp = File.createTempFile("ipresult", ".txt", new File(tmpfolder));
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
s = s.toString();
BufferedWriter writer = new BufferedWriter(new FileWriter(iptmp));
writer.write(s);
}
} catch (Exception ex) {
System.out.println(ex.getMessage().toString());
}
return isActive;
}
}
I want to write the result from the command in the temporary file, I found something related in other questions in this site, and it seems to work fine, but when I run this, the file is created with some random numers (ie: ipresult540677216848957037.txt) and it's empty, I can't figure out why, I also read that it's something related to java 1.7, so that means that I can't fill the file with information, there something that I'm missing?
Every time you open a file for writing that way -- i.e., every time you execute this line:
BufferedWriter writer = new BufferedWriter(new FileWriter(iptmp));
the file is truncated to zero length. Furthermore, since you never explicitly call close() on the BufferedWriter, line you do write will never actually be flushed to the file. As a result, no data ever makes it to the disk.
To do this correctly, first, move the line above to before the loop, so it only executes once. Second, after the loop, include code like
if (writer != null)
writer.close();
Finally, note that your program is needlessly broken on Macs, which are neither Linux, nor do they use cmd.exe. Instead of the way you've written this, you test explicitly for Windows, and use the Windows command line if you find it; otherwise, assume something UNIX-like, and use the Linux version.
You need to close the writer
BufferedReader stdInput = new BufferedReader(new InputStreamReader(
p.getInputStream()));
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter(iptmp));
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
s = s.toString();
writer.write(s);
}
} finally {
if (writer != null) {
writer.close();
}
}
If you are using java 7
try (BufferedWriter writer = new BufferedWriter(new FileWriter(
iptmp));) {
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
s = s.toString();
writer.write(s);
}
}