returning variable and saving to file
Hi :) my program downloads image links from www . I want the the image links wich are displaed to be also saved to text file on "c:\file.txt". I was looking for some examples but i couldnt do it, can someone help me and do this for me . At the end of code there's "return listaLinkow;" i want this results to be saved to text file. Thank you for help :)
Code :
package imagelinks;
import javax.jws.WebService;
import java.net.*;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.filechooser.*;
import javax.swing.*;
import java.io.*;
import java.util.*;
@WebService(targetNamespace = "http://imglinks/")
public class ImageLinks implements IImageLinks {
// sprawdz format URL
private static URL sprawdzUrl(String url) {
// tylko URLs. zaczynające się od http
if (!url.toLowerCase().startsWith("http://"))
return null;
URL sprawdzonyUrl = null;
try {
sprawdzonyUrl = new URL(url);
} catch (Exception e) {
return null;
}
return sprawdzonyUrl;
}
// Pobierz stronę o danym URL.
private static String downloadPage(URL pageUrl) {
try {
// Open connection to URL for reading.
BufferedReader reader = new BufferedReader(new InputStreamReader(pageUrl.openStream()));
// Read page into buffer.
String line;
StringBuffer pageBuffer = new StringBuffer();
while ((line = reader.readLine()) != null) {
pageBuffer.append(line);
}
return pageBuffer.toString();
}
catch (Exception e) {
}
return null;
}
private static ArrayList<String> pobierzImageLinks(String pageContents) {
ArrayList links = new ArrayList();
// 2 Pattern p = Pattern.compile("<\\s*img\\s[^>]*src\\s*=\\s*\"([^\\\"]*)(\")[^>]*>" , Pattern.CASE_INSENSITIVE);
Pattern p = Pattern.compile("<img [^>]*\\bsrc=\"([^\"]*)\"", Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(pageContents);
while (m.find()) {
String link = m.group(1).trim();
if (link.length() < 1) {
continue;
}
if (link.charAt(0) != 'h') {
continue;
}
links.add(link);
}
return links;
}
public ArrayList<String> getImageLinks(String strona) {
System.out.println("Pobranie linków z strony: " + strona);
URL url = sprawdzUrl(strona);
String zawartosc = downloadPage(url);
ArrayList listaLinkow = pobierzImageLinks(zawartosc);
return listaLinkow;
}
Re: returning variable and saving to file
What is the problem in your code?
Does it throw any exception?
No one here will write code for you. But we will teach you to go through the problems you have created in your code and will help you to solve them on your own by providing you hints.
Re: returning variable and saving to file
Hi,
I do not think there should be any problem to save the links in a file try google you can find your answer or simple append everytime the link in a file.
Core java