I am trying to telnet to a server, run a command and put the output of that command in a file.
I can get the command in the file but not the result of this command.
I cannot see my output on my console either, so I assumed it run but I am not sure.
Does anybody have any idea?
public final static void main(String[] args) throws IOException, InterruptedException
{
FileOutputStream fout = null;
try
{
fout = new FileOutputStream ("spyfile.log");
}
catch (IOException e)
{
System.err.println(
"Exception while opening the spy file: "
+ e.getMessage());
}
TelnetClient telnet;
telnet = new TelnetClient();
try
{
telnet.connect("myserver", 23);
}
catch (IOException e)
{
e.printStackTrace();
System.exit(1);
}
telnet.registerSpyStream(fout);
PrintStream out = new PrintStream( telnet.getOutputStream() );
out.println( "mycommand" );
try
{
telnet.disconnect();
}
catch (IOException e)
{
e.printStackTrace();
System.exit(1);
}
fout.close();
System.exit(0);
}
I am not sure what is TelneClient, if this is Commons Net class, then you are missing the part that actually reads data exchanged during telnet session. Please run this example and see how it works, once you get it you'll be able to cut it to your needs.
Related
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?
I have two classes - Provider and Requester:
Provider
import java.io.*;
import java.net.*;
public class Provider {
ServerSocket providerSocket;
Socket connection = null;
ObjectOutputStream out;
ObjectInputStream in;
String message;
Provider() {
}
void run() {
try {
// 1. creating a server socket
providerSocket = new ServerSocket(2004, 10);
// 2. Wait for connection
System.out.println("Waiting for connection");
connection = providerSocket.accept();
System.out.println(
"Connection received from " + connection.getInetAddress().getHostName());
// 3. get Input and Output streams
out = new ObjectOutputStream(connection.getOutputStream());
out.flush();
in = new ObjectInputStream(connection.getInputStream());
sendMessage("Connection successful");
// 4. The two parts communicate via the input and output streams
do {
try {
sendMessage(
"Please enter the phrase you wish to echo or the word FINISHED to exit");
message = (String) in.readObject();
sendMessage(message);
} catch (ClassNotFoundException classnot) {
System.err.println("Data received in unknown format");
}
} while (!message.equals("FINISHED"));
} catch (IOException ioException) {
ioException.printStackTrace();
} finally {
// 4: Closing connection
try {
in.close();
out.close();
providerSocket.close();
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
}
void sendMessage(String msg) {
try {
out.writeObject(msg);
out.flush();
System.out.println("server>" + msg);
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
public static void main(String args[]) {
Provider server = new Provider();
while (true) {
server.run();
}
}
}
Requester
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class Requester {
Socket requestSocket;
ObjectOutputStream out;
ObjectInputStream in;
String message;
Scanner input;
Requester() {
input = new Scanner(System.in);
}
void run() {
try {
// 1. creating a socket to connect to the server
requestSocket = new Socket("127.0.0.1", 2004);
System.out.println("Connected to localhost in port 2004");
// 2. get Input and Output streams
out = new ObjectOutputStream(requestSocket.getOutputStream());
out.flush();
in = new ObjectInputStream(requestSocket.getInputStream());
// 3: Communicating with the server
try {
message = (String) in.readObject();
System.out.println("server>" + message);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
do {
try {
message = (String) in.readObject();
System.out.println(message);
message = input.nextLine();
sendMessage(message);
message = (String) in.readObject();
} catch (ClassNotFoundException classNot) {
System.err.println("data received in unknown format");
}
} while (!message.equals("FINISHED"));
} catch (UnknownHostException unknownHost) {
System.err.println("You are trying to connect to an unknown host!");
} catch (IOException ioException) {
ioException.printStackTrace();
} finally {
// 4: Closing connection
try {
in.close();
out.close();
requestSocket.close();
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
}
void sendMessage(String msg) {
try {
out.writeObject(msg);
out.flush();
System.out.println("client>" + msg);
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
public static void main(String args[]) {
Requester client = new Requester();
client.run();
}
}
The programs are basically meant to communicate with each other. The idea is that they each 'connect' with each other via sockets and the user should be able to enter something in the console window of Provider and have it echoed back onto the console of Requester. However, I am getting the following errors:
Provider
java.net.SocketException: Permission denied: listen failed
Requester
java.net.ConnectException: Connection refused: connect
(I can provide the rest of the errors if it would help in fixing the issue).
I have tried having the classes in the same project folder, in separate folders, and in different workspaces. I have also tried using Eclipse EE (Neon) and the SE (Oxygen). Recently, I have been having problems with ports and sockets (most notably with Tomcat and encountering the 'Cannot find free socket for debugger' in Eclipse). Would that have something to do with me being unable to run these programs?
Check your firewall settings. I was having similar problems when trying to use sockets. Make sure any relevant resources aren't blocked.
You might also want to run the command:
netstat -ano | findstr :2004
to check if that port is mistakenly in use already.
when I use docx4j to generate doc from HTML and output through java servlet, it works well on Windows system, I can download and open the doc file normally.
When I put the project on Linux server, I can also download the doc file, but when openging file, it alert that the file is broken. I must click the confirm and restore the file.then open it normally.
my core code is like this.
how can i get the same result as windows?
code in jsp:
String vhtml = DownHtml2DocUtil.replaceSvgData2Base64(request);
response.reset();
response.setContentType("application/octet-stream");//设置为字节流
OutputStream output = null;
try {
output = response.getOutputStream();
response.addHeader("Content-Disposition", "attachment;filename=" + System.currentTimeMillis() + ".doc");
DownHtml2DocUtil.genDocFromHtml(vhtml, output);
} catch (Exception e) {
} finally {
try {
if (output != null) {
output.close();
}
} catch (Exception e) {
}
}
response.flushBuffer();
out.clear();
out = pageContext.pushBody();
code in java like this:
public static void genDocFromHtml(String html, OutputStream out)
throws EMPException {
try {
WordprocessingMLPackage wordMLPackage;
wordMLPackage = WordprocessingMLPackage.createPackage();
XHTMLImporterImpl XHTMLImporter = new XHTMLImporterImpl(
wordMLPackage);
wordMLPackage.getMainDocumentPart().getContent()
.addAll(XHTMLImporter.convert(html, "utf-8"));
// wordMLPackage.save(out); -- i tried both method
new Save(wordMLPackage).save(out);
} catch (InvalidFormatException e) {
throw new EMPException(e);
} catch (Docx4JException e) {
throw new EMPException(e);
} catch (Exception e) {
e.printStackTrace();
}
}
any suggestion will be appreciate , thanks anyway;
I'm a moderately-experienced C++ guy slowly learning Java. I'm writing a program which needs to do the following:
Create a simple text file, default directory is fine
As the program runs, periodically write one line of data to the file. Depending on a number of factors, the program may write to the file once or a million times. There is no way of knowing which write will be the last.
I've been researching different ways to do this, and this is the working code I've come up with. There are two files, "PeteProgram.java" and "PeteFileMgr.java" :
/*
"PeteProgram.java"
*/
import java.io.*;
import java.lang.String;
public class PeteProgram {
public static void main(String[] args) throws IOException {
String PeteFilename="MyRecordsFile.txt";
Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(PeteFilename), "utf-8"));
PeteFileMgr MyPeteFileMgr = new PeteFileMgr(writer);
MyPeteFileMgr.AddThisString(writer, "Add this line #1\n");
MyPeteFileMgr.AddThisString(writer, "Add this line #2\n");
MyPeteFileMgr.AddThisString(writer, "Add this line #3\n");
}
}
//=====================================================================================================
//=====================================================================================================
/*
"PeteFileMgr.java"
*/
import java.io.*;
public class PeteFileMgr {
public PeteFileMgr(Writer writer) {
try {
writer.write("File created!");
} catch (IOException ex) {
// report
} finally {
try {writer.close();} catch (Exception ex) {}
}
}
void AddThisString(Writer writer, String AddThis) {
try {
writer.append(AddThis);
} catch (IOException ex) {
// report
} finally {
try {writer.close();} catch (Exception ex) {}
}
}
}
The initial creation of the file works just fine. However, the to-be-added lines are not written into the file. Because the program compiles and runs with no errors, I assume the program tries to write the added lines, fails, and throws an exception. (Unfortunately, I am working with a primitive compiler/debugger and can't see if this is the case.)
Does anyone spot my mistake?
Many thanks!
-P
That's because you're not flushing the Writer. You should call flush from time to time. Also, you should close your Writer at the end of your app, not after writing content into it. close method automatically flushes the contents of the writer.
So, this is how your code should look like:
public class PeteProgram {
public static void main(String[] args) {
String peteFilename = "MyRecordsFile.txt";
//here's when the physical file is created
Writer writer = null;
try {
writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(peteFilename), "utf-8"));
PeteFileMgr peteFileMgr = new PeteFileMgr(writer);
peteFileMgr.addThisString(writer, "Add this line #1\n");
peteFileMgr.addThisString(writer, "Add this line #2\n");
peteFileMgr.addThisString(writer, "Add this line #3\n");
} catch (IOException e) {
//handle the exception
//basic handling
e.printStacktrace();
} finally {
//this is a must!
try { writer.close(); } catch(IOException silent) { }
}
}
}
public class PeteFileMgr {
public PeteFileMgr(Writer writer) {
try {
//this method is not creating the physical file
writer.write("File created!");
} catch (IOException ex) {
// report
} finally {
//remove this call to close
//try {writer.close();} catch (Exception ex) {}
}
}
public void addThisString(Writer writer, String addThis) {
try {
writer.append(addThis);
} catch (IOException ex) {
// report
} finally {
//remove this call to close
//try {writer.close();} catch (Exception ex) {}
}
}
}
Or if using Java 7 or superior using the try-with-resources:
public class PeteProgram {
public static void main(String[] args) {
String peteFilename = "MyRecordsFile.txt";
//here's when the physical file is created
try (Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(peteFilename), "utf-8"))) {
PeteFileMgr peteFileMgr = new PeteFileMgr(writer);
peteFileMgr.addThisString(writer, "Add this line #1\n");
peteFileMgr.addThisString(writer, "Add this line #2\n");
peteFileMgr.addThisString(writer, "Add this line #3\n");
} catch (IOException e) {
//handle the exception
//basic handling
e.printStacktrace();
}
}
}
I'd like to show my Console's output in a text file.
public static void main(String [ ] args){
DataFilter df = new DataFilter();
df.displayCategorizedList();
PrintStream out;
try {
out = new PrintStream(new FileOutputStream("C:\\test1.txt", true));
System.setOut(out);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I get my result correctly on the screen but not result in the textfile ?
the test file is genereted but it is empty??
You should print to "console" after you have set the system output stream into a file.
DataFilter df = new DataFilter();
PrintStream out;
try {
out = new PrintStream(new FileOutputStream("C:\\test1.txt", true));
System.setOut(out);
df.displayCategorizedList();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (out != null)
out.close();
}
Also use a finally block to always close the stream otherwise data might not be flushed to the file.
I would suggest the following approach:
public static void main(String [ ] args){
DataFilter df = new DataFilter();
try (PrintStream out = new PrintStream(new FileOutputStream("d:\\file.txt", true))) {
System.setOut(out);
df.displayCategorizedList();
} catch (FileNotFoundException e) {
System.err.println(String.format("An error %s occurred!", e.getMessage()));
}
}
This is using the JDK 7 try-with-resources feature - meaning that it deals with exceptions (like FileNotFoundException) that you have and it also closes the resources (instead of the finally block).
If you cannot use JDK 7, use one of the approaches suggested in the other responses.