how to copy the console output of this program in java - java

package prgms;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
class new_experi
{
public static void main(String[] args) throws IOException
{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter out = new BufferedWriter(new FileWriter("C://Users//Abhilasha U//Desktop//output.txt"));
try
{
Process p=Runtime.getRuntime().exec("cmd /c dir");
p.waitFor();
BufferedReader reader=new BufferedReader(
new InputStreamReader(p.getInputStream())
);
String line;
while((line = reader.readLine()) != null)
{
System.out.println(line);
}
}
catch(IOException e1) {}
System.out.println("Done");
}
}

Answer is simple.
package prgms;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
class new_experi
{
public static void main(String[] args) throws IOException
{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter out = new BufferedWriter(new FileWriter("C://Users//Abhilasha U//Desktop//output.txt"));
try
{
Process p=Runtime.getRuntime().exec("cmd /c dir");
p.waitFor();
BufferedReader reader=new BufferedReader(
new InputStreamReader(p.getInputStream())
);
String line;
while((line = reader.readLine()) != null)
{
System.out.println(line);
}
}
catch(IOException e1) {}
System.out.println("Done");
// This will pause your application so that you can take a screen shot !!
System.in.read();
}
}
If you are running this on an IDE, compile this program and run it. Once it is seen in the console. Press Alt + Print screen button then it will print screen your console.

Related

Error in receiving a html webpage by java

below code is for getting html web page
import java.net.*;
import java.io.*;
import java.io.File; // Import the File class
import java.io.IOException; // Import the IOException class to handle errors
public class TestClass2 {
public static void main(String[] args) throws Exception {
try{
URL url = new URL("https://stackoverflow.com/");
HttpURLConnection urlConnection=(HttpURLConnection)url.openConnection();
BufferedReader reader = new BufferedReader( new InputStreamReader(url.openStream()));
String line;
while ((line = reader.readLine()) != null)
{
System.out.println(line+"\n");
}
reader.close();
}catch(Exception ex){
System.out.println(ex);
}
}
}
but when compile and run that below error occur:
javax.net.ssl.SSLException: Received fatal alert: protocol_version.
how can fix it?
thanks.
This could be that the SSL Certificate is out of date? Have you tried using HttpsURLConnection? Try this first
Revised Code
import java.net.*;
import java.io.*;
import java.io.File; // Import the File class
import java.io.IOException; // Import the IOException class to handle errors
public class TestClass2 {
public static void main(String[] args) throws Exception {
try{
URL url = new URL("https://stackoverflow.com/");
HttpsURLConnection urlConnection=(HttpsURLConnection)url.openConnection();
BufferedReader reader = new BufferedReader( new InputStreamReader(url.openStream()));
String line;
while ((line = reader.readLine()) != null)
{
System.out.println(line+"\n");
}
reader.close();
}catch(Exception ex){
System.out.println(ex);
}
}
}

how to run Run a linux command(curl) through java and to get the xml response

I want to execute a Linux command (curl) using java code
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class ExecuteShellCommand {
public String executeCommand(String command) {
StringBuffer output = new StringBuffer();
Process p;
try {
p = Runtime.getRuntime().exec(command);
p.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = reader.readLine()) != null) {
output.append(line + "\n");
}
} catch (Exception e) {
e.printStackTrace();
}
return output.toString();
}
public static void main(String args[]) {
ExecuteShellCommand com = new ExecuteShellCommand();
System.out.println(com.executeCommand(
"curl -u '<username><pw>' -k <host>/services/search/jobs -d search=\"abc""));
System.out.println("hello");
The console output is printing hello only with no errors though when i tried the command in git bash it will give a xml response.

How to read strings and numbers from file in java?

How to read from a file strings or numbers with one space between them.
You can just write a class which will read a file and remove the spaces.
package com.example.removespaces
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class RemoveSpacesInFileEx {
public static void main(String[] args) throws FileNotFoundException, IOException {
FileReader fr = new FileReader("input.txt");
BufferedReader br = new BufferedReader(fr);
FileWriter fw = new FileWriter("outfile.txt");
String line;
while((line = br.readLine()) != null)
{
line = line.trim();
line=line.replaceAll("\\s+", " ");
fw.write(line);
}
fr.close();
fw.close();
}
}
public void readData() {
File file = new File("file.txt"); //You can put your file name or your file position here
try {
Scanner sc = new Scanner(file);
while(sc.hasNext()) {
System.out.println(sc.nextLine());
} System.out.println();
}
catch (FileNotFoundException e) {
System.out.println(e.getMessage());
}
System.out.println("End of the Main");
} //This will read it from a file and print on your console

Client/Server in java : Program gets stuck upon input of second file name

I am developing code to send multiple file names to server side and then making sure server recieves those contents and writes it to a file in its own folder. Its working well when I type first file name but when I type second file name the code kind of gets stuck.
Here is my client code:-
package fileTransfer;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class EchoClient {
public static void main(String[] args) throws UnknownHostException {
try {
Socket clientSock=new Socket("localhost",8888);
//to read from server
BufferedReader br=new BufferedReader(new InputStreamReader(clientSock.getInputStream())); //to read
//to write to server
PrintWriter pw=new PrintWriter(clientSock.getOutputStream(), true);
//for user input
BufferedReader userIn=new BufferedReader(new InputStreamReader(System.in));
BufferedReader fileContent=null;
String str=null;
String fileContentLine=null;
while(true){
if((str=br.readLine()).contains("file name")) //recieve echo from server
System.out.println(str);
str=userIn.readLine(); //read user input
fileContent=new BufferedReader(new FileReader(str));
pw.println(str);
while((fileContentLine=fileContent.readLine()) != null){
pw.println(fileContentLine);
}
while((str=br.readLine())!=null)
System.out.println(str);
pw.flush();
}
}catch(IOException e){
e.printStackTrace();
}
}
}
And here is my server code
package fileTransfer;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class EchoServer {
public static void main(String[] args){
try {
ServerSocket serverSock=new ServerSocket(8888);
System.out.println("Waiting for client");
Socket connectFromClient=serverSock.accept();
File file=null;
//reading data from client
BufferedReader input=new BufferedReader(new InputStreamReader(connectFromClient.getInputStream()));
//will write back to client
PrintWriter pr=new PrintWriter(new OutputStreamWriter(connectFromClient.getOutputStream()));
PrintWriter writeToFile=null;
//sending following statements to client
pr.println("Connection established with server! Give a file name");
pr.flush();
String response;
while(true){
while((response=input.readLine()) != null)
{
if(response==null)
break;
else{
System.out.println(response);
if(response.contains(".txt")){
//file=new File("FromClient.txt");
file=new File("FromClient"+response);
if(!file.exists())
file.createNewFile();
writeToFile=new PrintWriter(file);
}
else{
//writeToFile=new PrintWriter(file);
writeToFile.println(response);
}
pr.println("Echo from server -> " + response);
//System.out.println("Adding these contents to a file");
writeToFile.flush();
pr.flush();
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
It´s getting stuck in the client in this lines:
while ((str = br.readLine()) != null) {
System.out.println(str);
}
Waiting for more server lines.
You have to tell the client when to stop from reading file data from socket stream and jump for the next file. For instance you can send before the content of the file the number of bytes you are going to transfer, you read that number of bytes from the stream and then go for the next file.
I post this modifications of your code as an example, as the idea I want to express.
First I get the total linenumber of the file (I suppose text file), and I send it to server, which knows exactly how many lines to read before jumping to next file.
It can be changed to use the total size of the file in bytes, for instance.
This code is no 100% correct, it works, take it as an example.
Client:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class EchoClient {
public static void main(final String[] args) throws UnknownHostException {
try {
final Socket clientSock = new Socket("localhost", 8888);
// to read from server
final BufferedReader br = new BufferedReader(new InputStreamReader(clientSock.getInputStream())); // to
// read
// to write to server
final PrintWriter pw = new PrintWriter(clientSock.getOutputStream(), true);
// for user input
final BufferedReader userIn = new BufferedReader(new InputStreamReader(System.in));
BufferedReader fileContent = null;
String str = null;
String fileContentLine = null;
while (true) {
System.out.println("Print filename");
str = userIn.readLine(); // read user input
fileContent = new BufferedReader(new FileReader(str));
pw.println(str);
// first count the line number:
int lineno = 0;
while ((fileContentLine = fileContent.readLine()) != null) {
lineno++;
}
fileContent.close();
//
fileContent = new BufferedReader(new FileReader(str));
pw.println(String.valueOf(lineno));
while ((fileContentLine = fileContent.readLine()) != null) {
pw.println(fileContentLine);
}
for (int i = 0; i < lineno; i++) {
str = br.readLine();
System.out.println(str);
}
pw.flush();
}
} catch (final IOException e) {
e.printStackTrace();
}
}
}
Server:
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class EchoServer {
public static void main(final String[] args) {
try {
final ServerSocket serverSock = new ServerSocket(8888);
System.out.println("Waiting for client");
final Socket connectFromClient = serverSock.accept();
File file = null;
// reading data from client
final BufferedReader input = new BufferedReader(new InputStreamReader(connectFromClient.getInputStream()));
// will write back to client
final PrintWriter pr = new PrintWriter(new OutputStreamWriter(connectFromClient.getOutputStream()));
PrintWriter writeToFile = null;
// sending following statements to client
pr.println("Connection established with server! Give a file name");
pr.flush();
String response;
while (true) {
final String fileName = input.readLine();
file = new File("FromClient" + fileName);
if (!file.exists()) {
file.createNewFile();
}
writeToFile = new PrintWriter(file);
final String sLineNo = input.readLine();
final int lineno = Integer.parseInt(sLineNo);
for (int i = 0; i < lineno; i++) {
response = input.readLine();
System.out.println(response);
// writeToFile=new PrintWriter(file);
writeToFile.println(response);
pr.println("Echo from server -> " + response);
// System.out.println("Adding these contents to a file");
writeToFile.flush();
pr.flush();
}
writeToFile.close();
}
} catch (final IOException e) {
e.printStackTrace();
}
}
}
I Hope to be helpful.

Java TCP Client Server Hangs Up?

I am currently having difficulty understanding why my code is not working. I've included my client and server code below. I've figured out that my problem happens somewhere in the while loops but I'm not sure how to fix it so that it doesn't get stuck. I've searched around the forum for a while and some said adding a newline character would fix it, but I'm still having trouble.
My main question is how can I avoid the process from getting stuck and not communicating properly. Can anybody out there point me in the right direction?
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;
public class My_Client {
public static void main(String[] args) throws UnknownHostException, IOException {
Socket s = new Socket("localhost", 5555);
BufferedReader r = new BufferedReader(new InputStreamReader(
s.getInputStream()));
PrintStream w = new PrintStream(s.getOutputStream());
w.print("hello world");
w.print('\n');
String line;
while ((line = r.readLine()) != null) {
System.out.println("Received: " + line);
//System.out.println("Error");
}
w.close();
}
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
-----------------------------------------------------------------
public class My_Server {
private static final int PORT = 5555;
public static void main(String[] args) {
try {
ServerSocket ss = new ServerSocket(PORT);
System.out.println("Server Socket Created");
while (true) {
System.out.println("Waiting on connection");
Socket cs = ss.accept();
System.out.println("Client connected");
BufferedReader r = new BufferedReader(new InputStreamReader(
cs.getInputStream()));
PrintStream w = new PrintStream(cs.getOutputStream());
String line;
while ((line = r.readLine()) != null) {
w.print(line + "!!!!");
w.print('\n');
}
System.out.println("Client disconnected");
r.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Both ends are reading until EOS and neither is closing until after that. So you have a classic deadlock. You need to rethink your application protocol.
You also need to tell your PrintStream or PrintWriter to autoflush, or else call flush() yourself, but this is a relatively minor matter compared to the mistake above.
You should use autoflush on your PrintWriters like this:
PrintStream w = new PrintStream(cs.getOutputStream(),true);
You can setup a PROTOCOL to end the communication something like this:
In your client:
w.println("[END]");
In your server:
while (!(line = r.readLine()).equals("[END]")) {
Hope this helps:
Check the comments
And be sure that you get Client Connected on console of server side
CLIENT SIDE
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;
public class My_Client {
public static void main(String[] args) throws UnknownHostException, IOException {
Socket s = new Socket("localhost", 5555);
BufferedReader r = new BufferedReader(new InputStreamReader(
s.getInputStream()));
PrintStream w = new PrintStream(s.getOutputStream());
w.print("hello world");
w.print("\n"); // enter new line
w.flush();// flush the outputstream
String line;
while ((line = r.readLine()) != null) {
System.out.println("Received: " + line);
//System.out.println("Error");
}
w.close();
}
}
SERVER SIDE
----------------------------------------------------------
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
public class My_Server {
private static final int PORT = 5555;
public static void main(String[] args) {
try {
ServerSocket ss = new ServerSocket(PORT);
System.out.println("Server Socket Created");
while (true) {
System.out.println("Waiting on connection");
Socket cs = ss.accept();
System.out.println("Client connected");
BufferedReader r = new BufferedReader(new InputStreamReader(
cs.getInputStream()));
PrintStream w = new PrintStream(cs.getOutputStream());
String line;
while ((line = r.readLine()) != null) {
w.print(line + "!!!!");
w.print("\n");// entering new line
}
System.out.println("Client disconnected");
r.close();
w.close();// close w
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

Categories