I am trying to print out any changes that is appended at the end of a log file, similar to tail log. But when printing it out with printwriter it will also print out a new line.
Instead of printing
test1
test2
it prints:
test1
test2
Code is as below. I tried with pwriter.print(line) instead of println but nothing is printed. Is there any way to remove the carriage return.
public class Lognow implements Runnable{
boolean execute = true;
InputStreamReader inputStreamReader;
BufferedReader bufferedReader;
PrintWriter pwriter;
public Lognow(){
PrintWriter pw = new PrintWriter(System.out, true);
try {
inputStreamReader = new InputStreamReader(new FileInputStream ("D:/app/logi.txt"));
bufferedReader = new BufferedReader (inputStreamReader);
String line = bufferedReader.readLine();
while(line!=null){
line = bufferedReader.readLine();
}
pwriter = pw;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
while( execute ) {
try {
String str="";
String line = bufferedReader.readLine();
if(line!=null) {
pwriter.println(line);
}
else {
try {
Thread.sleep( 500 );
}
catch( InterruptedException ex )
{
execute = false;
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void main(String[] args){
Lognow lognow = new Lognow();
lognow.run();
}
Don't use println(). Use print() instead, and flush().
Related
I have a batch and shell script that execute MYSQL command.
mysql -u user -p < path\etc\script\db\dosomething.sql
I have a java program that uses ProcessBuilder to execute the batch script.
I am aware that this command will prompt the user for the password , I am also aware that I can alternatively use the --password (which throws an unsafe warning) or a config file to set the login parameters.
I want to provide the password using the input prompt via ProcessBuilder but when I run the program it just hangs and I have no idea why.
When I use JVisualVM to view what is happening I notice that the OutputStream thread is not running and if it did then what is hanging the program ? Below is my implementation:-
Class that deals with the InputStream and ErrorStream :
public static class InStream extends Thread {
private final InputStream in;
private final PrintWriter pw;
public InStream(InputStream in, PrintWriter pw, String threadName) {
super(threadName);
this.in = in;
this.pw = pw;
}
#Override
public void run() {
try (BufferedReader br = new BufferedReader(new InputStreamReader(in));) {
String line;
while ((line = br.readLine()) != null) {
if (Thread.currentThread().isInterrupted()) {
Thread.currentThread().interrupt();
break;
}
pw.println(line);
pw.flush();
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
try {
in.close();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
}
}
Class that deals with the OutputStream:
public static class OutStream extends Thread {
private final String message;
private final OutputStream out;
public OutStream(OutputStream out, String threadName, String message) {
super(threadName);
this.out = out;
this.message = message;
}
#Override
public void run() {
try (PrintWriter pw = new PrintWriter(out);) {
pw.println(message);
pw.flush();
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
try {
out.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
Here is the main program:
public static void main(String[] args) {
try {
String password = "Y0urp#ssw0rd";
ProcessBuilder builder = new ProcessBuilder("path\\etc\\script\\cli\\batchWithSQLCommand.bat");
Process process = builder.start();
StringWriter errors = new StringWriter();
StringWriter input = new StringWriter();
new OutStream(process.getOutputStream(), "output-stream-thread", password).start();
new InStream(process.getErrorStream(), new PrintWriter(errors, true), "error-stream-thread").start();
new InStream(process.getInputStream(), new PrintWriter(input, true), "input-stream-thread").start();
process.waitFor();
System.out.println("inputStream: " + input.toString());
System.out.println("Error Stream: " + errors.toString());
} catch (IOException | InterruptedException ex) {
//throw error here
} catch (Error | Exception ex) {
//throw error here
}
}
What could be the problem ?
I wrtite parser without third-party libraries. Get html code from web site - http://www.cnn.com/ - but some part of code has unicode instead symbols, for example: "\u003cbr/>Sign in to your TV service provider to get access to \u003cbr/>" i think it is problem with encode - how i can fix it? Sorry for my English. Thank you.
public class Main {
public static void main(String[] args) throws IOException {
String commandLine = Scraper.readLineFromConsole();
Reader reader = Scraper.getReader(commandLine);
Scraper.writeInFileFromURL(reader);
}
public static class Scraper {
public static void writeInFileFromURL(Reader out) {
Reader reader = out;
BufferedReader br = new BufferedReader(reader);
try {
PrintWriter writer = new PrintWriter("newFile.txt");
String htmltext;
while (br.ready()) {
htmltext = br.readLine();
writer.write(new String(htmltext));
}
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static String readLineFromConsole() {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String commandLine = null;
try {
commandLine = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return commandLine;
}
public static Reader getReader(String url)
throws IOException {
// Retrieve from Internet.
if (url.startsWith("http:") || url.startsWith("https:")) {
URLConnection conn = new URL(url).openConnection();
return new InputStreamReader(conn.getInputStream());
}
// Retrieve from file.
else {
return new FileReader(url);
}
}
}
}
Am using nio2 to read the external file in my desktop using eclipse. I am getting the exception for the following code.
"java.nio.file.NoSuchFileException: C:\Users\User\Desktop\JEE\FirstFolder\first.txt"
Kindly advise how to resolve it? Tried using command prompt also. Getting the same exception.
public class ReadingExternalFile {
public static void main(String[] args) {
Path p1= Paths.get("C:\\Users\\User\\Desktop\\FirstFolder\\first.txt");
System.out.println(p1.toString());
System.out.println(p1.getRoot());
try(InputStream in = Files.newInputStream(p1);
BufferedReader reader = new BufferedReader(new InputStreamReader(in)))
{
System.out.println("Inside try");
String line=null;
while((line=reader.readLine())!=null){
if (!line.equals("")) {
System.out.println(line);
}
//System.out.println(line);
}
} catch (IOException e) {
System.out.println( e);
}
}
}
I dont understand why you are using a Path object, you can simply make the file using the File object and just using the string as the path, and then wraping it in a file reader object then wrapping that in a buffered reader, the end should look something like this:
public static void main(String[] args) {
try {
File file = new File("C:\\Users\\User\\Desktop\\FirstFolder\\first.txt");
FileReader fr = new FileReader(file);
BufferedReader bfr = new BufferedReader(fr);
System.out.println(bfr.readLine());
bfr.close();
} catch (IOException e){
e.printStackTrace();
}
}
don't forget to close your streams after reading and writing, also use readable names (don't do what I've done, use meaningful names!)
Try below code hope this will help you.
Path p1= Paths.get("C:\\Users\\user\\Desktop\\FirstFolder\\first.txt");
try(
BufferedReader reader = Files.newBufferedReader(p1, Charset.defaultCharset()))
{
System.out.println("Inside try");
String line=null;
while((line=reader.readLine())!=null){
if (!line.equals("")) {
System.out.println(line);
}
//System.out.println(line);
}
} catch (IOException e) {
System.out.println( e);
}
Try this.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class BufferedReaderExample {
public static void main(String[] args) {
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("C:\\Users\\User\\Desktop\\FirstFolder\\first.txt"));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
public static void main(String[] args) {
try {
File file = new File("C:\\Users\\User\\Desktop\\FirstFolder\\first.txt");
FileReader freader = new FileReader(file);
BufferedReader bufreader = new BufferedReader(freader);
System.out.println(bufreader.readLine());
bufreader.close();
} catch (IOException e){
e.printStackTrace();
}
}
I'm trying to search a word specified in the command line from a file. However, when it is being run, it displays nothing. What could the problem be? Here is a part of my code. Thank you for helping me!
class ClientHandler extends Thread {
private Socket client;
private Scanner input;
private PrintWriter output;
private ArrayList<String> quotes;
public ClientHandler3(Socket socket, String file) {
client = socket;
try {
BufferedReader buffer = new BufferedReader(new FileReader(file));
BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
String line = reader.readLine();
try {
int ctr = 0;
quotes = new ArrayList<String>();
while(line != null){
quotes.add(ctr, line);
ctr++;
line = buffer.readLine();
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
input = new Scanner(client.getInputStream());
output = new PrintWriter(client.getOutputStream(), true);
}
catch(IOException e) {
e.printStackTrace();
}
}
public void run(String[] args) {
String target;
String message = "";
target= args[3];
for(int i = 0; i<quotes.size(); i++){
if(quotes.get(i).toUpperCase().contains(target.toUpperCase())){
output.println(quotes.get(i));
}
}
output.println("|");
try {
if (client != null) {
System.out.println("Closing down connection...");
client.close();
}
}
catch(IOException e) {
System.out.println("Unable to disconnect!");
}
}
}
Your client reads args[1] (the host), args[2] (the port), but not args[3], the word to be searched.
Your code is also hard to read, because it doesn't respect the standard naming conventions. Classes start with an uppercase letter, whereas methods start with a lowercase letter. Your code does the inverse.
Here is my sample code, I want to handle the command from standard input while running a new sub process. However, the exec method never returns if I read the system.in. The command in the exec() is very simple and has nothing to do with the stdin.
I'm wondering about is there any way to solve this? How can I start a new sub process while start another thread reading stdin?
public static void main(String[] args){
new Thread(new Runnable(){
public void run(){
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String command = null;
try{
while((command = reader.readLine()) != null){
System.out.println("Command Received:" + command);
}
}catch(Exception ex){
ex.printStackTrace();
//failed to listening command
}
}
}).start();
Process process = null;
try {
process = Runtime.getRuntime().exec("java -cp C:/agenttest Test");
System.out.println("never returns");
process.waitFor();
} catch (IOException e) {
throw new RuntimeException( e );
} catch (InterruptedException e) {
throw new RuntimeException( e );
}
}
The Test class is very simple, here is the Test.java
public static void main(String[] args){
System.out.println("Standard out");
System.out.println("Standard out");
System.err.println("Standard err");
System.out.println("Standard out");
try{
Thread.sleep(10000);
}catch(InterruptedException ex){}
}
The problem could be that you're not handling the error stream and input stream and are overrunning the platform's buffers. Try handling that output as per the famous article, When Runtime.exec() won't.
For example:
import java.io.*;
public class TestMain {
private static final String JAVA_CMD = "java";
private static final String CP = "-cp";
// *** your CLASS_PATH and PROG Strings will of course be different ***
private static final String CLASS_PATH = "C:/Users/hovercraft/Documents/workspace/Yr 2012A/bin";
private static final String PROG = "yr12.m07.b.Test2";
private static final String[] CMD_ARRAY = { JAVA_CMD, CP, CLASS_PATH, PROG };
public static void main(String[] args) {
new Thread(new Runnable() {
public void run() {
BufferedReader reader = new BufferedReader(new InputStreamReader(
System.in));
String command = null;
try {
while ((command = reader.readLine()) != null) {
System.out.println("Command Received:" + command);
}
} catch (Exception ex) {
ex.printStackTrace();
// failed to listening command
}
}
}).start();
Process process = null;
try {
ProcessBuilder processBuilder = new ProcessBuilder(CMD_ARRAY);
process = processBuilder.start();
InputStream inputStream = process.getInputStream();
setUpStreamGobbler(inputStream, System.out);
InputStream errorStream = process.getErrorStream();
setUpStreamGobbler(errorStream, System.err);
System.out.println("never returns");
process.waitFor();
} catch (IOException e) {
throw new RuntimeException(e);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
public static void setUpStreamGobbler(final InputStream is, final PrintStream ps) {
final InputStreamReader streamReader = new InputStreamReader(is);
new Thread(new Runnable() {
public void run() {
BufferedReader br = new BufferedReader(streamReader);
String line = null;
try {
while ((line = br.readLine()) != null) {
ps.println("process stream: " + line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}).start();
}
}
You should keep reading the input stream, otherwise it will get blocked. It has nothing to do with JVM but the underyling operating system.