Exam code:
import java.net.*;
import java.io.*;
public class CheckMail {
public static void main(String s[]) {
//
// CheckMail [mailServer] [user] [password]
//
try {
CheckMail t = new CheckMail();
int i = t.checkMyMail(s[0], s[1], s[2]);
if (i==0) {
System.out.println("No mail waiting.");
}
else {
System.out.println
("There " + (i==1?"is " :"are ") + i +
" message" +(i==1?"":"s")+ " waiting.");
}
}
catch (Exception e) {
e.printStackTrace();
}
}
private void send(BufferedWriter out, String s) throws IOException {
out.write(s+"\n");
out.flush();
}
private String receive(BufferedReader in) throws IOException {
return in.readLine();
}
private int checkMyMail
(String server, String user, String pass) throws IOException {
Socket s = new Socket(server, 110);
BufferedReader in = new BufferedReader(
new InputStreamReader(s.getInputStream()));
BufferedWriter out = new BufferedWriter(
new OutputStreamWriter(s.getOutputStream()));
receive(in);
send(out, "USER " + user);
receive(in);
send(out, "PASS " + pass);
receive(in);
return getNumberOfMessages(in, out);
}
public int getNumberOfMessages
(BufferedReader in, BufferedWriter out) throws IOException {
int i = 0;
String s;
send(out, "LIST");
receive(in);
while((s = receive(in)) != null) {
if (!(s.equals("."))) {
i++;
}
else
return i;
}
return 0;
}
}
Done! Happy Coding!
Related posts:
Java Program to Implement the Vigenere Cypher
Java Program to Describe the Representation of Graph using Incidence List
Guide to Java Instrumentation
Collect a Java Stream to an Immutable Collection
Life Cycle of a Thread in Java
Spring Cloud AWS – Messaging Support
REST Pagination in Spring
Hamcrest Collections Cookbook
Giới thiệu java.io.tmpdir
Java Program to Implement Dijkstra’s Algorithm using Queue
Java Program to Compute Determinant of a Matrix
Java Program to Implement Queue
Query Entities by Dates and Times with Spring Data JPA
Guide to BufferedReader
Java Program to Find the Vertex Connectivity of a Graph
Java Program to Decode a Message Encoded Using Playfair Cipher
Spring Boot - Flyway Database
Guide to the Volatile Keyword in Java
Java Program to Check whether Undirected Graph is Connected using BFS
Prevent Brute Force Authentication Attempts with Spring Security
Java Program to Implement AVL Tree
Hướng dẫn Java Design Pattern – Interpreter
The DAO with Spring and Hibernate
Sử dụng Fork/Join Framework với ForkJoinPool trong Java
Java Program to Implement ArrayBlockingQueue API
Quick Guide to java.lang.System
Adding Parameters to HttpClient Requests
Java Program to Implement Slicker Algorithm that avoids Triangulation to Find Area of a Polygon
Encode/Decode to/from Base64
Spring Boot - Cloud Configuration Server
Ignore Null Fields with Jackson
Debug a JavaMail Program