Tuesday, March 22, 2016

Java Execute Systed Command in Linux and File I/O

Java Execute Systed Command in Linux

Runtime r = Runtime.getRuntime();
Process p = r.exec("uname -a");
p.waitFor();
BufferedReader b = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";

while ((line = b.readLine()) != null) {
  System.out.println(line);
}

b.close();

 JAVA open a file for appending


Are you doing this for logging purposes? If so there are several libraries for this. Two of the most popular are Log4j and Logback.
If you just want something simple, this will work:

Java 7

If you just need to do this one time, the Files class makes this easy:
try {
    Files.write(Paths.get("myfile.txt"), "the text".getBytes(), StandardOpenOption.APPEND);
}catch (IOException e) {
    //exception handling left as an exercise for the reader
}
However, if you will be writing to the same file many times, the above has to open and close the file on the disk many times, which is a slow operation. In this case, a buffered writer is better:
try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("myfile.txt", true)))) {
    out.println("the text");
    //more code
    out.println("more text");
    //more code
}catch (IOException e) {
    //exception handling left as an exercise for the reader
}
Notes:
  • The second parameter to the FileWriter constructor will tell it to append to the file (as opposed to writing a new file).
  • Using a BufferedWriter is recommended for an expensive writer (such as FileWriter).
  • Using a PrintWriter gives you access to println syntax that you're probably used to from System.out.
  • But the BufferedWriter and PrintWriter wrappers are not strictly necessary.
 

No comments:

Post a Comment