Client.java
try {
try {
br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
received = br.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("In-Cmd = " + received);
} finally {
try {
br.close();
} catch (Exception e) {}
}
Server.java
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new OutputStreamWriter(connectionSocket.getOutputStream()));
System.out.println("Out-Cmd = STOP");
bw.write("stop");
bw.newLine();
} finally {
try {
bw.close();
} catch (Exception exp) {}
}
So, what happen is that I have this GUI where the client can upload the file from their local hardrive to the server, and then we will copy the file and store them in the server.
I can send BufferWriter from Client to Server no problem at all, but when I want to do from Server to Client I always receive null
Am I doing something wrong?
Related
I want to create a folder structure to connected URL location. I am able read file from connected URL location, but note able to create a folder. Here is my code to read file from URL.
public class ReadFromURL {
public static void main(String[] args) {
// TODO Auto-generated method stub
String urlToConnect = "http://11.111.111.2/UploadedFiles/test/";
String boundary = Long.toHexString(System.currentTimeMillis()); // Just generate some unique random value.
URLConnection connection = null;
URL url = null;
try {
url= new URL("http://11.111.111.2/UploadedFiles/test");
connection = url.openConnection();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
connection.setDoOutput(true); // This sets request method to POST.
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
int responseCode = 0;
try {
responseCode = ((HttpURLConnection) connection).getResponseCode();
URL url1 = new URL("http://11.111.111.2/UploadedFiles/test/test.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(url1.openStream()));
String FILENAME = "D:\\test\\filename.txt";
// write the output to stdout
String line;
while ((line = reader.readLine()) != null)
{
write_to_file(FILENAME,line);
System.out.println(line);
}
// close our reader
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(responseCode);
}
public static void write_to_file(String filename,String line)
{
BufferedWriter bw = null;
FileWriter fw = null;
try {
//String content = "This is the content to write into file\n";
fw = new FileWriter(filename);
bw = new BufferedWriter(fw);
bw.write(line);
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bw != null)
bw.close();
if (fw != null)
fw.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
I have created a program to convert text to xml by using ReverseXSL API.
This program is to be executed by an application by calling static method (static int transformXSL).
I am able to execute and produce output with running from Eclipse. However, When I ran program (jar) by using application it stuck somewhere and I couldnt find anything.
Then, I debugged by "Debug as...-> Remote Java Application" in Eclipse from Application and found "InvocationTargetException" at ClassLoaders.callStaticFunction.
Below Static method is called by application.
public class MyTest4 {
public MyTest4()
{
}
public static int transformXSL(String defFile, String inputFile, String XSLFile, String OutputFile) {
System.out.println("Dheeraj's method is called");
// start time
FileWriter fw=null;
try {
fw = new FileWriter("D://Countime.txt");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
BufferedWriter output=new BufferedWriter(fw);
DateFormat sd=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Date dt= new Date();
System.out.println("Date is calculated");
try {
output.write("Start Time:"+sd.format(dt).toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(sd.format(dt));
FileReader myDEFReader=null, myXSLReader=null;
TransformerFactory tf = TransformerFactory.newInstance();
Transformer t=null;
FileInputStream inStream = null;
ByteArrayOutputStream outStream = null;
// Step 1:
//instantiate a transformer with the specified DEF and XSLT
if (new File(defFile).canRead())
{
try {
myDEFReader = new FileReader(defFile);
System.out.println("Definition file is read");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
else myDEFReader = null;
if (new File(XSLFile).canRead())
try {
myXSLReader = new FileReader(XSLFile);
System.out.println("XSL file is read");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
else myXSLReader = null;
try {
t = tf.newTransformer(myDEFReader, myXSLReader);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Step 1: DEF AND XSLT Transformation completed");
// Step 2:
// Read Input data
try {
inStream = new FileInputStream(inputFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
outStream = new ByteArrayOutputStream();
System.out.println("Step 2: Reading Input file: completed");
// Step 3:
// Transform Input
try {
try (BufferedReader br = new BufferedReader(new FileReader("D://2.txt"))) {
String line = null;
while ((line = br.readLine()) != null) {
System.out.println("Content: "+line);
}
}
System.out.println("File: "+inputFile.toString());
System.out.println("\n content: \n"+ inStream.toString());
System.out.println("Calling Transform Function");
t.transform(inStream, outStream);
System.out.println("Transformation is called");
outStream.close();
try(OutputStream outputStream = new FileOutputStream(OutputFile)) {
outStream.writeTo(outputStream);
System.out.println("Outstream is generated; Output file is creating");
}
System.out.println(outStream.toString());
} catch (TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FactoryConfigurationError e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TransformerFactoryConfigurationError e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (javax.xml.transform.TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("output file is created");
// End time
Date dt2= new Date();
System.out.println(sd.format(dt2));
System.out.println("End time:"+dt2.toString());
try {
output.append("End Time:"+sd.format(dt2).toString());
output.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return 0;
}
}
Forgive me if the question is stupid, but I cannot move the reader to a second line. Calling function on every input line is important.
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader("input.txt"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while ((reader.readLine()) != null) {
///////////
}
Try that:
BufferedReader reader = null;
try {
String line;
reader = new BufferedReader(new FileReader("input.txt"));
while ((line = reader.readLine()) != null) {
myFunc (line);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (reader!=null)
try {
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
You can also use a Scanner instead:
File file = new File ("input.txt");
Scanner scanner = null;
try {
scanner = new Scanner(file);
while (scanner.hasNextLine()) {
myFunc (scanner.nextLine());
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (scanner!=null)
scanner.close();
}
You just need to store the value returned by reader.readLine into an additional variable (just like I said in my comment). Modify your code to look like the following:
String line = null;
while ((line = reader.readLine()) != null) {
//use "line" as per your needs
}
I have a Java Server and one(or more) Android Clients. For now I want them to communicate simply with strings. When i write from android I can get the data in Java Server, but when I try to get the answer from server the Android application stop working. The codes is reported below:
Java Server:
public class Server {
private static int port=12346, maxConnections=0;
// Listen for incoming connections and handle them
public static void main(String[] args) {
int i=0;
try{
ServerSocket listener = new ServerSocket(port);
Socket server;
while((i++ < maxConnections) || (maxConnections == 0)){
doComms connection;
server = listener.accept();
String end = server.getInetAddress().toString();
System.out.println("\n"+end+"\n");
doComms conn_c= new doComms(server);
Thread t = new Thread(conn_c);
t.start();
}
} catch (IOException ioe) {
System.out.println("IOException on socket listen: " + ioe);
ioe.printStackTrace();
}
}
}
class doComms implements Runnable {
private Socket server;
private String line,input;
public doComms(Socket server) {
this.server=server;
}
#SuppressWarnings("deprecation")
public void run () {
input="";
try {
// Get input from the client
DataInputStream in = new DataInputStream (server.getInputStream());
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(server.getOutputStream())),
true);
while((line = in.readLine()) != null && !line.equals(".")) {
input=input + line;
}
JOptionPane.showMessageDialog(null, input);
out.println("Enviado");
server.close();
} catch (IOException ioe) {
System.out.println("IOException on socket listen: " + ioe);
ioe.printStackTrace();
}
}
And Android client's code (it's called every time a button is pressed inside onClick method):
public String enviaMensagem(){
String resposta="";
new Thread(new ClientThread()).start();
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
try {
socket = new Socket(ip, port);
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream.writeUTF(input.getText().toString());
resposta = dataInputStream.readUTF();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
if (socket != null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataOutputStream != null){
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataInputStream != null){
try {
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return resposta;
}
You are using an unsorted mixture of readUTF(), writeUTF(), readLine(), etc. They're not all interoperable. Settle on one of them. If you use writeUTF() you must use readUTF() at the other end. If you use readLine() you must write lines at the other end, with a line terminator such as \r\n or \n.
This question already has answers here:
Problem with "scopes" of variables in try catch blocks in Java
(3 answers)
Closed last year.
I have omitted irrelevant parts of the code:
[...]
try {
URL url = new URL(updateUrl);
BufferedReader input = new BufferedReader(new InputStreamReader(url.openStream()));
[...]
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
} finally {
input.close();
}
[...]
The problem is that on the finally "input.close()" Eclipse says that "input cannot be resolved".
I think it may be an scope problem, but I have seen code from other guys and it has usually this same form, so I do not know why it is not working here.
Any hints?
Thanks a lot in advance,
It is indeed a scope error.
Your input is declared inside the try block, so it can't be seen inside the finally block. Declare it outside, so that it is visible to both, and you should be fine:
[...]
BufferedReader input = null;
try {
URL url = new URL(updateUrl);
input = new BufferedReader(new InputStreamReader(url.openStream()));
[...]
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
} finally {
if (input != null)
{
try {
input.close();
}
catch (IOException exc)
{
exc.printStackTrace();
}
}
}
[...]
declare BufferedReader input instance globally or outside first try/catch block as:
[...]
BufferedReader input;
try {
URL url = new URL(updateUrl);
input = new BufferedReader(new InputStreamReader(url.openStream()));
[...]
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
} finally {
input.close();
}
[...]
You're right, it is a scope problem. Java uses block scope, which means local variables declared in one scope are invisible in any scope that is not contained within it. try blocks and finally blocks are not exceptions to this rule.
BufferedReader input;
try {
URL url = new URL(updateUrl);
input = new BufferedReader(new InputStreamReader(url.openStream()));
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
// Log or ignore this
}
}
}