How to create a folder structure in URL using java? - java

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();
}
}
}
}

Related

Java - Improve method (try/catch)

I have a method for retrieving some coordinates from a very slow page.
My method works fine but i cant help to feel like it can be greatly improved, specially the try/catch clauses.
The method looks like this:
public void getCoordinates(){
EventQueue.invokeLater(() -> loadingLabel.updateCoordinates(true));
consolePanel.getConsole().append("\nRetrieving coordinates from server\n");
shapes.clear();
URL url = null;
try {
url = new URL("http://TestServlet/");
} catch (MalformedURLException e) {
e.printStackTrace();
consolePanel.getConsole().append(e.toString());
}
try {
URLConnection connection = url.openConnection();
connection.setConnectTimeout(1000);
try (InputStream dataSource = url.openStream()) {
BufferedReader inputStream = new BufferedReader(new InputStreamReader(
dataSource, StandardCharsets.ISO_8859_1));
double xCoordinate;
double yCoordinate;
String line;
while ((line = inputStream.readLine()) != null) {
if(!line.startsWith("#")) {
consolePanel.getConsole().append(line + "\n");
String[] text = line.split(",");
xCoordinate = Double.parseDouble(text[0]);
yCoordinate = Double.parseDouble(text[1]);
xCoordinate = Math.abs(xCoordinate)/4;
yCoordinate = Math.abs(yCoordinate)/4;
String name = text[2];
shapes.add(this.mapPanelState.getNewShape(xCoordinate, yCoordinate, 10, name));
}
}
}
} catch (IOException e) {
e.printStackTrace();
consolePanel.getConsole().append(e.toString());
}
EventQueue.invokeLater(this::repaint);
EventQueue.invokeLater(() -> loadingLabel.updateCoordinates(false));
}
Any help to improve on it would be much appreciated.
Your error handling is the same for both catch clauses. So you may easily merge those.
public void getCoordinates() {
try {
URL url = new URL("http://TestServlet/");
URLConnection connection = url.openConnection();
connection.setConnectTimeout(1000);
try (InputStream dataSource = url.openStream()) {
BufferedReader inputStream = new BufferedReader(new InputStreamReader(dataSource, StandardCharsets.ISO_8859_1));
double xCoordinate;
double yCoordinate;
String line;
while ((line = inputStream.readLine()) != null) {
if (!line.startsWith("#")) {
consolePanel.getConsole().append(line + "\n");
String[] text = line.split(",");
xCoordinate = Double.parseDouble(text[0]);
yCoordinate = Double.parseDouble(text[1]);
xCoordinate = Math.abs(xCoordinate) / 4;
yCoordinate = Math.abs(yCoordinate) / 4;
String name = text[2];
shapes.add(this.mapPanelState.getNewShape(xCoordinate, yCoordinate, 10, name));
}
}
}
} catch (Exception e) {
e.printStackTrace();
consolePanel.getConsole().append(e.toString());
}
EventQueue.invokeLater(this::repaint);
EventQueue.invokeLater(() -> loadingLabel.updateCoordinates(false));
}
Here is my improvement:
try {
URL url = new URL("http://TestServlet/");
URLConnection connection = url.openConnection();
connection.setConnectTimeout(1000);
try (InputStream dataSource = url.openStream()) {
BufferedReader inputStream = new BufferedReader(new InputStreamReader(
dataSource, StandardCharsets.ISO_8859_1));
/*
your logic here
*/
}
} catch (MalformedURLException e) {
e.printStackTrace();
//consolePanel.getConsole().append("URL is malformed! Try with a valid one");
} catch (IOException e) {
e.printStackTrace();
//consolePanel.getConsole().append("....");
} catch (Exception e) {
// runtime exceptions
}
If your action does not change whether it's a MalformedURLException, IOException etc., the following catch block is enough:
catch (Exception e) {
e.printStackTrace();
//consolePanel.getConsole().append(e.toString());
}

Convert Windows-1252 file into UTF-8 file

Hello I am having some issues with this simple task of conversion.
Here is my code bellow (rough but not so complex):
FileInputStream fis = new FileInputStream ("file");
BufferedReader reader = new BufferedReader(new InputStreamReader(fis,"CP1250"));
try {
StringBuilder sb = new StringBuilder();
String line = null;
try {
line = reader.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while (line != null) {
sb.append(line);
if(line.contains(" "))
sb.append(System.lineSeparator());
try {
line = reader.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
String everything = sb.toString();
System.out.println(everything);
PrintWriter writer = null;
try {
writer = new PrintWriter("clean", "UTF-8");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
writer.println(everything);
writer.close();
}
finally {
try {
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
But I get the same output as the input with the same encoding format.
Do you see anyway able to help?
The docs say that
1) public void println(String x)
Prints a String and then terminates the line. This method behaves as though it invokes print(String) and then println().
And 2)
public void print(String s)
Prints a string. If the argument is null then the string "null" is printed. Otherwise, the string's characters are converted into bytes according to the platform's default character encoding, and these bytes are written in exactly the manner of the write(int) method.
You probably will get your conversion done with
PrintWriter writer
= new PrintWriter(new OutputStreamWriter(new FileOutputStream("clean", true),
"UTF-8"));

How to read a line from text file, call function on that line and move to second line and so on?

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
}

BufferedReader and BufferedWriter in Java null

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?

I want know how I can write my InputStream content to an XML file (android)

Hey I have the following code:
import java.net.*;
import java.io.*;
class OpenStreamTest {
public static void main(String args[]) {
try {
URL yahoo = new URL("http://www.yahoo.com/");
DataInputStream dis;
String inputLine;
dis = new DataInputStream(yahoo.openStream());
while ((inputLine = dis.readLine()) != null) {
System.out.println(inputLine);
}
dis.close();
} catch (MalformedURLException me) {
System.out.println("MalformedURLException: " + me);
} catch (IOException ioe) {
System.out.println("IOException: " + ioe);
}
}
}
How can i save the source code i get from this to a XML file? Please help
Create a Connection:
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpGet httppost = new HttpGet("http://www.google.com");
HttpResponse response = httpclient.execute(httppost);
HttpEntity ht = response.getEntity();
BufferedHttpEntity buf = new BufferedHttpEntity(ht);
InputStream is = buf.getContent();
Put inputstream in a buffer and read it:
BufferedReader r = new BufferedReader(new InputStreamReader(is2));
total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line);
}
Then put it in the file:
File file = new File("/sdcard", "report.xml");
if(!file.exists()){
file.createNewFile();
}
StringBuilder temp = null;
while ((inputLine = dis.readLine()) != null) {
temp.append(inputLine);
}
FileWriter fw = new FileWriter(file);
fw.write(temp.toString());
fw.flush();
Hope this helpes
Here is an example, where "iso" is you InputSrteam
try {
final File file = new File("/sdcard/filename.xml");
final OutputStream output = new FileOutputStream(file);
try {
try {
final byte[] buffer = new byte[1024];
int read;
while ((read = iso.read(buffer)) != -1)
output.write(buffer, 0, read);
output.flush();
}
finally {
output.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
iso.close();
System.out.println("saved");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

Categories

Resources