当先锋百科网

首页 1 2 3 4 5 6 7

Java是一种广泛应用于软件开发领域的编程语言。以下是一些Java的应用领域和工程示例:

1. 网络应用

public class HttpServer {
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket(8080);
System.out.println("Listening for connection on port 8080...");
while (true) {
Socket client = server.accept();
InputStreamReader isr = new InputStreamReader(client.getInputStream());
BufferedReader br = new BufferedReader(isr);
String request = br.readLine();
if (request != null) {
System.out.println(request);
}
String response = "Hello from Java http server!";
DataOutputStream out = new DataOutputStream(client.getOutputStream());
out.writeBytes("HTTP/1.1 200 OK\r\n");
out.writeBytes("Content-Type: text/html\r\n");
out.writeBytes("Content-Length: " + response.length() + "\r\n");
out.writeBytes("\r\n");
out.writeBytes(response);
out.close();
br.close();
client.close();
}
}
}

上面这段代码演示了如何使用Java编写一个简单的HTTP服务器,可以用于搭建网站。

2. 移动应用

public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView webView = findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("https://www.google.com");
}
}

这段代码是在Android平台上使用Java编写的,在一个Activity中嵌入了一个WebView,然后展示了Google的网站。

3. 数据库应用

public class Main {
public static void main(String[] args) throws SQLException {
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root", "root");
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("SELECT * FROM users");
while (resultSet.next()) {
String name = resultSet.getString("name");
String email = resultSet.getString("email");
System.out.println(name + ": " + email);
}
connection.close();
}
}

这段代码展示了如何使用Java编写一个简单的数据库应用程序,通过JDBC连接MySQL数据库,并执行一些查询操作。