/** * Connects to the remote machine by establishing a tunnel through a HTTP proxy with Basic * authentication. It issues a CONNECT request and authenticates with the HTTP proxy with Basic * protocol. * * @param address remote machine to connect to * @return a TCP/IP socket connected to the remote machine * @throws IOException if an I/O error occurs during handshake (a network problem) */ private Socket authenticateBasic(InetSocketAddress address, ConnectivitySettings cs) throws IOException { Socket proxy = new Socket(cs.getProxyHost(), cs.getProxyPort()); BufferedReader r = new BufferedReader( new InputStreamReader(new InterruptibleInputStream(proxy.getInputStream()))); DataOutputStream dos = new DataOutputStream(proxy.getOutputStream()); String username = cs.getProxyUsername() == null ? "" : cs.getProxyUsername(); String password = cs.getProxyPassword() == null ? "" : String.valueOf(cs.getProxyPassword()); String credentials = username + ":" + password; String basicCookie = Base64Encoder.encode(credentials.getBytes("US-ASCII")); dos.writeBytes("CONNECT "); dos.writeBytes(address.getHostName() + ":" + address.getPort()); dos.writeBytes(" HTTP/1.0\r\n"); dos.writeBytes("Connection: Keep-Alive\r\n"); dos.writeBytes("Proxy-Authorization: Basic " + basicCookie + "\r\n"); dos.writeBytes("\r\n"); dos.flush(); String line = r.readLine(); if (sConnectionEstablishedPattern.matcher(line).find()) { for (; ; ) { line = r.readLine(); if (line.length() == 0) break; } return proxy; } throw new IOException("Basic authentication failed: " + line); }
public static String sendGet(String url, String params) { String result = ""; BufferedReader in = null; try { String urlName = url + "?" + params; URL realUrl = new URL(urlName); URLConnection conn = realUrl.openConnection(); conn.setRequestProperty("accept", "*/*"); conn.setRequestProperty("connection", "Keep-Alive"); conn.setRequestProperty( "user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)"); conn.connect(); Map<String, List<String>> map = conn.getHeaderFields(); for (String key : map.keySet()) { System.out.println(key + "--->" + map.get(key)); } in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = in.readLine()) != null) { result += "\n" + line; } } catch (Exception e) { e.printStackTrace(); } finally { try { if (in != null) { in.close(); } } catch (IOException ex) { ex.printStackTrace(); } } return result; }
static void fun() { PrintStream toSoc; try { ServerSocket f = new ServerSocket(9090); while (true) { Socket t = f.accept(); BufferedReader fromSoc = new BufferedReader(new InputStreamReader(t.getInputStream())); String video = fromSoc.readLine(); System.out.println(video); searcher obj = new searcher(); boolean fs; fs = obj.search(video); if (fs == true) { System.out.println("stream will starts"); toSoc = new PrintStream(t.getOutputStream()); toSoc.println("stream starts"); } else { toSoc = new PrintStream(t.getOutputStream()); toSoc.println("sorry"); } } } catch (Exception e) { System.out.println(e); } }
// ********************************************************************************** // // Theoretically, you shouldn't have to alter anything below this point in this file // unless you want to change the color of your agent // // ********************************************************************************** public void getConnected(String args[]) { try { // initial connection int port = 3000 + Integer.parseInt(args[1]); s = new Socket(args[0], port); sout = new PrintWriter(s.getOutputStream(), true); sin = new BufferedReader(new InputStreamReader(s.getInputStream())); // read in the map of the world numNodes = Integer.parseInt(sin.readLine()); int i, j; for (i = 0; i < numNodes; i++) { world[i] = new node(); String[] buf = sin.readLine().split(" "); world[i].posx = Double.valueOf(buf[0]); world[i].posy = Double.valueOf(buf[1]); world[i].numLinks = Integer.parseInt(buf[2]); // System.out.println(world[i].posx + ", " + world[i].posy); for (j = 0; j < 4; j++) { if (j < world[i].numLinks) { world[i].links[j] = Integer.parseInt(buf[3 + j]); // System.out.println("Linked to: " + world[i].links[j]); } else world[i].links[j] = -1; } } currentNode = Integer.parseInt(sin.readLine()); String myinfo = args[2] + "\n" + "0.7 0.45 0.45\n"; // name + rgb values; i think this is color is pink // send the agents name and color sout.println(myinfo); } catch (IOException e) { System.out.println(e); } }
public boolean shutdown(int port, boolean ssl) { try { String protocol = "http" + (ssl ? "s" : ""); URL url = new URL(protocol, "127.0.0.1", port, "shutdown"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("servicemanager", "shutdown"); conn.connect(); StringBuffer sb = new StringBuffer(); BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8")); int n; char[] cbuf = new char[1024]; while ((n = br.read(cbuf, 0, cbuf.length)) != -1) sb.append(cbuf, 0, n); br.close(); String message = sb.toString().replace("<br>", "\n"); if (message.contains("Goodbye")) { cp.appendln("Shutting down the server:"); String[] lines = message.split("\n"); for (String line : lines) { cp.append("..."); cp.appendln(line); } return true; } } catch (Exception ex) { } cp.appendln("Unable to shutdown CTP"); return false; }
/** @return lines read from server. */ private static String[] getResponse(String clientId, String clientCommand, Socket server) throws IOException { try { /** Create filter I/O streams for the socket, Open our connection to server port . */ InputStreamReader inputStreamReader = new InputStreamReader(server.getInputStream()); BufferedReader fromServer = new BufferedReader(inputStreamReader); PrintStream toServer = new PrintStream(server.getOutputStream()); // Send machine name or IP address to server: toServer.println(clientId + " " + clientCommand); toServer.flush(); /** Read lines of response from the server,and block while synchronously waiting: */ final int lines = 2; String[] response = new String[lines]; for (int i = 0; i < lines; i++) { String textFromServer = fromServer.readLine(); response[i] = textFromServer; if (textFromServer == null) { throw new IOException("unable to read from server, end of the stream has been reached"); } else { System.out.println(textFromServer); } } return response; } catch (IOException x) { throw x; } }
void writeoneline(String filename1, String filename2) throws IOException { // open the file for reading BufferedReader file = new BufferedReader(new FileReader(filename1)); String line = null; // send message System.out.println("Sending message to the server..."); while ((line = file.readLine()) != null) { String onebyone = line; output.println(onebyone); } file.close(); // open the file for reading PrintWriter file2 = new PrintWriter(new BufferedWriter(new FileWriter(filename2))); String line2 = input.readLine(); // receive a message // String response = input.readLine(); if (line2.isEmpty()) System.out.println("(server did not reply with a message)"); else { System.out.println("Writing to file...:"); // String line= null; file2.println(line2); file2.close(); } System.out.println("Done!"); }
/** @param args the command line arguments */ public static void main(String[] args) { try { int randomNum = (int) ((Math.random() * 100) + 1); Socket server = new Socket("127.0.0.1", 8888); BufferedReader input = new BufferedReader(new InputStreamReader(server.getInputStream())); PrintWriter output = new PrintWriter(server.getOutputStream(), true); String leggi; int total = 0; output.println(randomNum); while ((leggi = input.readLine()) != null) { System.out.println("Valore letto: " + leggi); total += Integer.parseInt(leggi); } System.out.println("Somma dei valori ricevuti dal Server: " + total); if (total % 2 == 0) { System.out.println("PARI"); } else { System.out.println("DISPARI"); } } catch (UnknownHostException ex) { System.out.println("Errore indirizzo sconosciuto:" + ex.getMessage()); } catch (IOException ex) { System.out.println(ex); } }
private String handleConnection() { String content = null; try { PrintWriter streamWriter = new PrintWriter(connection.getOutputStream()); BufferedReader streamReader = new BufferedReader(new InputStreamReader(connection.getInputStream())); content = streamReader.readLine(); // System.out.println(content); log.debug("receiveing begin............\r\n"); log.debug(content); log.debug("receiveing end........"); streamWriter.println(content + "\r\n"); // streamWriter.println("hello\r\n"); streamWriter.flush(); streamReader.close(); streamWriter.close(); // connection.close(); return content; } catch (FileNotFoundException e) { // System.out.println("Could not find requested file on the server."); log.error("Could not find requested file on the server."); return content; } catch (IOException e) { // System.out.println("Error handling a client: " + e); log.error("Error handling a client: " + e); return content; } }
/** Starts receiving and broadcasting messages. */ public void run() { PrintWriter out = null; try { out = new PrintWriter(new OutputStreamWriter(incoming.getOutputStream())); // inform the server of this new client ChatServer.this.addClient(out); out.print("Welcome to JavaChat! "); out.println("Enter BYE to exit."); out.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(incoming.getInputStream())); for (; ; ) { String msg = in.readLine(); if (msg == null) { break; } else { if (msg.trim().equals("BYE")) break; System.out.println("Received: " + msg); // broadcast the receive message ChatServer.this.broadcast(msg); } } incoming.close(); ChatServer.this.removeClient(out); } catch (Exception e) { if (out != null) { ChatServer.this.removeClient(out); } e.printStackTrace(); } }
/** * create a Bufferedreader that read from the open url The parameter of the search term research * can be setup using the various command */ private boolean download() { buffer = new StringBuilder(); // --1. Encode url? // --2. Do the work try { url = new URL(composite_url); // Config.log("ESearch for: "+search_term); } catch (MalformedURLException e) { Config.log("Error: URL is not good.\n" + composite_url); } try { if (in_connection_open) in_connection.close(); in_connection = new BufferedReader(new InputStreamReader(url.openStream())); if (in_connection != null) in_connection_open = true; String inputLine = ""; if (isOutputToDisk()) output = new PrintWriter(new FileWriter(new File(filename))); while ((inputLine = in_connection.readLine()) != null) { if (!this.isOutputToDisk()) { buffer.append(inputLine + "\n"); } else { output.println(inputLine); } } if (isOutputToDisk()) { output.flush(); output.close(); } } catch (IOException e) { Config.log("Unable to download from..." + composite_url); return false; } return true; }
private String getAddressXY(String x, String y) { try { StringBuilder text = new StringBuilder(); String url = properties.getProperty("geocoderUrl"); String param1 = properties.getProperty("geocoderUrlParam1"); String param2 = properties.getProperty("geocoderUrlParam2"); url = url + "?" + param1 + "=" + x + "&" + param2 + "=" + y; URL page = new URL(url); HttpURLConnection urlConn = (HttpURLConnection) page.openConnection(); urlConn.connect(); InputStreamReader in = new InputStreamReader((InputStream) urlConn.getContent()); BufferedReader buff = new BufferedReader(in); String line = buff.readLine(); while (line != null) { text.append(line); line = buff.readLine(); } String result = text.toString(); buff.close(); in.close(); return result; } catch (MalformedURLException e) { windowServer.txtErrors.append(e.getMessage() + "\n"); return ""; } catch (Exception e) { windowServer.txtErrors.append(e.getMessage() + "\n"); return ""; } }
private void processRequest() throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); DataOutputStream writer = new DataOutputStream(socket.getOutputStream()); try { request.parseRequest(reader); } catch (HttpRequestException e) { System.out.println(e.getMessage()); ResponseCode = 400; ResponseReason = "Bad Request"; } if (isCrawlingRequest()) { CrawlerHandler crawler = new CrawlerHandler(GetDomainFromRequest()); crawler.StartCrawling(); } checkTypeOfResponse(); writer.write(createHTTPResponseHeaders().getBytes()); writer.write(createHTTPResponseBody(writer)); writer.write(CRLF.getBytes()); writer.flush(); writer.close(); reader.close(); }
public static void main(String args[]) throws IOException { try { // Create a URL object String temp = "http://ccnabaaps.hostingsiteforfree.com/folder/phppart.php?q=http://www.espncricinfo.com/india/content/player/253802.html"; URL url = new URL(temp); // Read all of the text returned by the HTTP server BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String htmlText; while ((htmlText = in.readLine()) != null) { // Keep in mind that readLine() strips the newline characters System.out.println(htmlText); } in.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
public void firstRun() throws Exception { Socket sock = new Socket(host, new Integer(port).intValue()); OutputStream os = sock.getOutputStream(); String get = "GET " + contextRoot + "/test.jsp" + " HTTP/1.0\n"; System.out.println(get); os.write(get.getBytes()); os.write("\n".getBytes()); InputStream is = sock.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); // Get the JSESSIONID from the response String line = null; while ((line = br.readLine()) != null) { System.out.println(line); if (line.startsWith("Set-Cookie:") || line.startsWith("Set-cookie:")) { break; } } if (line == null) { throw new Exception("Missing Set-Cookie response header"); } String jsessionId = getSessionIdFromCookie(line, JSESSIONID); // Store the JSESSIONID in a file FileOutputStream fos = new FileOutputStream(JSESSIONID); OutputStreamWriter osw = new OutputStreamWriter(fos); osw.write(jsessionId); osw.close(); stat.addStatus(TEST_NAME, stat.PASS); }
private String ask(String cmd) { BufferedWriter out = null; BufferedReader in = null; Socket sock = null; String ret = ""; try { System.out.println(server); sock = new Socket(server, ServerListener.PORT); out = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream())); out.write(cmd, 0, cmd.length()); out.flush(); in = new BufferedReader(new InputStreamReader(sock.getInputStream())); int inr = in.read(); while (inr != ';') { ret += Character.toString((char) inr); inr = in.read(); } } catch (IOException io) { io.printStackTrace(); } finally { try { out.close(); in.close(); sock.close(); } catch (IOException io) { io.printStackTrace(); } } return ret; }
/** * Main run loop for the Receiver. Continuously reads from input until a null is passed, * terminating the receiver. */ public void run() { try // main run loop { String line; while ((line = input.readLine()) != null) { world.receive(name, line); } } catch (SocketException se) { world.setMessage("Your opponent has disconnected."); } catch (Exception e) { e.printStackTrace(); } // end loop try // terminating { world.destroySocket(name); input.close(); socket.close(); } catch (Exception e) { } System.out.println(getName() + " terminating"); }
private ServerSocketDemo() { try { ss = new ServerSocket(2002); s = ss.accept(); System.out.println("Server started"); local = new BufferedReader(new InputStreamReader(System.in)); remote = new BufferedReader(new InputStreamReader(s.getInputStream())); ps = new PrintStream(s.getOutputStream()); while (true) { System.out.println("Type a message to send to the client"); String localdata = local.readLine(); ps.println(localdata); // sends the data to output stream String remotedata = remote.readLine(); System.out.println("Client:= " + remotedata); if (remotedata.equals("bye")) { System.out.println("Client Disconnected"); break; } } } catch (Exception e) { System.out.println("Error in Server" + e); } }
public Server() { try { ServerSocket ss = new ServerSocket(SERVER_PORT); Socket s = ss.accept(); InputStream is = s.getInputStream(); OutputStream out = s.getOutputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String sss = br.readLine(); System.out.println(sss); PrintWriter pw = new PrintWriter(out); pw.print("hello,我是服务器。"); pw.close(); br.close(); isr.close(); out.close(); is.close(); s.close(); ss.close(); } catch (UnknownHostException ue) { ue.printStackTrace(); } catch (IOException oe) { oe.printStackTrace(); } }
/** * A asynchronous method for reading the content of the file. * * @return the content of the file, or an empty string when there's nothing in the file. */ public String getFileContent() { InputStream stream = getClass().getResourceAsStream(COOKIE); // The cookie file doesn't exist if (stream == null) return ""; BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); String line = null; try { // only one line is needed line = reader.readLine(); reader.close(); } catch (IOException e) { return ""; } // Line can't continue to be processed. if (line == null) return ""; // hasn't got an updateID yet. if (updateID == null) { setUpdateID(line); return line; } else { // The updateID hasn't been updated yet. if (updateID.equals(extractUpdateID(line))) return ""; // There is a new updateID in the file, so update it. else { setUpdateID(line); return line; } } }
// прочитать весь json в строку private static String readAll() throws IOException { StringBuilder data = new StringBuilder(); try { HttpURLConnection con = (HttpURLConnection) ((new URL(PRODUCT_URL).openConnection())); con.setRequestMethod("GET"); con.setDoInput(true); String s; try (BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()))) { while ((s = in.readLine()) != null) { data.append(s); } } } catch (MalformedURLException e) { e.printStackTrace(); throw new MalformedURLException("Url is not valid"); } catch (ProtocolException e) { e.printStackTrace(); throw new ProtocolException("No such protocol, it must be POST,GET,PATCH,DELETE etc."); } catch (IOException e) { e.printStackTrace(); throw new IOException("cannot read from server"); } return data.toString(); }
private String getTitle(File f) { String result = ""; if (!f.getName().endsWith(".html")) return "not HTML"; else { try { BufferedReader reader = new BufferedReader(new FileReader(f)); String ligne = reader.readLine(); while (ligne != null && !ligne.contains("<TITLE>") && !ligne.contains("<title>")) { ligne = reader.readLine(); } reader.close(); if (ligne == null) return "No TITLE in page " + f.getName(); else { String fin = ""; String debut = ""; if (ligne.contains("</TITLE>")) { debut = "<TITLE>"; fin = "</TITLE>"; } else if (ligne.contains("</title>")) { debut = "<title>"; fin = "</title>"; } else return "No title in page " + f.getName(); int fin_index = ligne.lastIndexOf(fin); result = ligne.substring(ligne.indexOf(debut) + 7, fin_index); return result; } } catch (Exception e) { LOG.error("Error while reading file " + e); return "Error for file " + f.getName(); } } }
private void readProblemInfo(String pathName) { ProblemManager problemManager = new ProblemManager(); File file = new File(pathName); try (BufferedReader br = new BufferedReader(new FileReader(file))) { String line; while ((line = br.readLine()) != null) { String[] sp = line.split(","); String input = MyUtil.readFromFile(new File(sp[1])); String output = MyUtil.readFromFile(new File(sp[2])); int timeLimit = Integer.valueOf(sp[3]); int memoryLimit = Integer.valueOf(sp[4]); String judgeMethod = ""; if (sp.length == 6) judgeMethod = MyUtil.readFromFile(new File(sp[5])); Map<String, String> pinfo = new HashMap<String, String>(); this.problems.put(sp[0], new ProblemInfo(sp[0], timeLimit, memoryLimit, 0)); pinfo.put("problem_id", sp[0]); pinfo.put("time_limit", String.valueOf(timeLimit)); pinfo.put("memory_limit", String.valueOf(memoryLimit)); pinfo.put("special_judge", judgeMethod); pinfo.put("input", input); pinfo.put("output", output); pinfo.put("time_stamp", "0"); problemManager.addEntry(pinfo); } } catch (IOException e) { e.printStackTrace(); System.exit(1); } }
/** * Empfaengt einen String (blockiert solange, bis der eingestellte TimeOut ueberschritten wurde) * ueber die Socket-Verbindung vom Communicator-Objekt des Clients. * * @return <code>String</code> empfangene Daten */ public String receive() throws InterruptedIOException, IOException { String s; int len; char[] c; StringWriter w = new StringWriter(); PrintWriter result = new PrintWriter(w); // falls nichts zu lesen ist s = in.readLine(); if (s == null) return null; // zuerst L"ange der zu empfangenen Daten lesen, dann Daten selbst len = Integer.parseInt(s); c = new char[len]; if (in.read(c, 0, len) == -1) System.out.println("ServerThread " + myNumber + " : error reading from socket!"); /* * while (s.equals("")) { while(in.ready()) { * result.print(in.readLine()); if (in.ready()) result.println(); } * result.flush(); w.flush(); s = w.toString(); } */ return new String(c); }
private boolean handshake() throws Exception { URL homePage = new URL("http://mangaonweb.com/viewer.do?ctsn=" + ctsn); HttpURLConnection urlConn = (HttpURLConnection) homePage.openConnection(); urlConn.connect(); if (urlConn.getResponseCode() == HttpURLConnection.HTTP_NOT_FOUND) return (false); // save the cookie String headerName = null; for (int i = 1; (headerName = urlConn.getHeaderFieldKey(i)) != null; i++) { if (headerName.equals("Set-Cookie")) { cookies = urlConn.getHeaderField(i); } } // save cdn and crcod String page = "", line; BufferedReader stream = new BufferedReader(new InputStreamReader(urlConn.getInputStream(), "UTF-8")); while ((line = stream.readLine()) != null) page += line; cdn = param(page, "cdn"); crcod = param(page, "crcod"); return (true); }
@Override public void run() { // System.out.println ("New Communication Thread Started"); try { BufferedReader in; // OUTPUT STREAM try (PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true)) { in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); String inputLine; // READ NUMBER OF FORTUNE COOKIES CLIENT WANTS while ((inputLine = in.readLine()) != null) { // System.out.println("Hello"); if (inputLine.equals("Bye.")) break; int number = Integer.parseInt(inputLine); System.out.println("Server: " + inputLine); // SENDS RANDOMLY GENERATED COOKIES out.println(new FortuneCookies().getCookies(number)); } } // CLIENT CLOSE in.close(); clientSocket.close(); } catch (IOException e) { System.err.println("Problem with Communication Server"); System.exit(1); } }
private void sourcesMenu() throws IOException { System.out.println("List of all known sources"); for (int i = 0; i < repo.getSources().size(); i++) { System.out.println(repo.getSources().get(i)); } System.out.println("Enter 1 or 'add' to add a source."); System.out.println("Enter 0 or 'back' to return to the main menu."); input = in.readLine(); if (input.equals("0") || input.equals("back")) { name = MenuName.MAIN; } else if (input.equals("1") || input.equals("add")) { System.out.println("Please enter the URL or filepath to the source."); System.out.println("Enter 0 or 'back' to return to the source menu."); input = in.readLine(); if (input.equals("0") || input.equals("back")) { return; } try { repo.getSources().add((new URL(input))); System.out.println("Source has been added to the repository."); } catch (MalformedURLException me) { System.out.println("Invalid URL or file path."); } } }
public void secondRun() throws Exception { // Read the JSESSIONID from the previous run FileInputStream fis = new FileInputStream(JSESSIONID); BufferedReader br = new BufferedReader(new InputStreamReader(fis)); String jsessionId = br.readLine(); new File(JSESSIONID).delete(); Socket sock = new Socket(host, new Integer(port).intValue()); OutputStream os = sock.getOutputStream(); String get = "GET " + contextRoot + "/ResumeSession" + " HTTP/1.0\n"; System.out.println(get); os.write(get.getBytes()); String cookie = "Cookie: " + jsessionId + "\n"; os.write(cookie.getBytes()); os.write("\n".getBytes()); InputStream is = sock.getInputStream(); br = new BufferedReader(new InputStreamReader(is)); String line = null; boolean found = false; while ((line = br.readLine()) != null) { System.out.println(line); if (line.contains(EXPECTED_RESPONSE)) { found = true; break; } } if (found) { stat.addStatus(TEST_NAME, stat.PASS); } else { throw new Exception("Wrong response. Expected response: " + EXPECTED_RESPONSE + " not found"); } }
public void run() { System.out.println("New Communication Thread Started"); try { PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); String inputLine; String[] inputTemp = new String[3]; while ((inputLine = in.readLine()) != null) { System.out.println("Server: " + inputLine); out.println(inputLine); if (inputLine.equals("Bye.")) break; } out.close(); in.close(); clientSocket.close(); } catch (IOException e) { System.err.println("Problem with Communication Server"); System.exit(1); } }
private String ReadWholeFileToString(String filename) { File file = new File(filename); StringBuffer contents = new StringBuffer(); BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(file)); String text = null; // repeat until all lines is read while ((text = reader.readLine()) != null) { contents.append(text).append(System.getProperty("line.separator")); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (reader != null) { reader.close(); } } catch (IOException e) { e.printStackTrace(); } } // show file contents here return contents.toString(); }