21xrx.com
2025-03-29 03:17:49 Saturday
文章检索 我的文章 写文章
如何让Java程序输出?
2023-06-15 15:24:57 深夜i     13     0
Java程序 输出 控制台 文件 网络

当我们学习Java编程时,第一步肯定是学习如何让计算机运行我们的程序。而程序的输出是我们必不可少的一部分,因为它可以让我们更加直观地了解程序的运行情况。下面我们就来看一下如何让Java程序输出。

1. 在控制台输出

使用Java的System.out.println()语句可以在控制台输出指定内容。例如:

public class HelloWorld {
 public static void main(String[] args) {
  System.out.println("Hello World!");
 }
}

这个程序会在控制台输出“Hello World!”这句话。

2. 输出到文件

除了在控制台输出,我们还可以把程序输出到文件中。Java提供了FileWriter类和PrintWriter类来实现这一功能。例如:

try {
 FileWriter fileWriter = new FileWriter("output.txt");
 PrintWriter printWriter = new PrintWriter(fileWriter);
 printWriter.println("Hello World!");
 printWriter.close();
} catch (IOException e) {
 e.printStackTrace();
}

这个程序会将“Hello World!”写入名为output.txt的文件中。

3. 输出到网络

有时候我们需要将程序的输出发送到网络中,比如发送电子邮件、发送短信等。Java提供了JavaMail API和Java Message Service API来实现这一功能。例如:

// 发送邮件
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
 protected PasswordAuthentication getPasswordAuthentication() {
  return new PasswordAuthentication("youremail@gmail.com", "yourpassword");
 }
});
try {
 Message message = new MimeMessage(session);
 message.setFrom(new InternetAddress("youremail@gmail.com"));
 message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("recipientemail@gmail.com"));
 message.setSubject("Testing Subject");
 message.setText("Hello World!");
 Transport.send(message);
 System.out.println("Sent message successfully...");
} catch (MessagingException e) {
 throw new RuntimeException(e);
}
// 发送短信
SmsSender smsSender = new SmsSender();
smsSender.sendSms("+1234567890", "Hello World!");

这个程序会发送一封包含“Hello World!”消息的电子邮件,并将“Hello World!”发送到+1234567890的手机号码。

  
  

评论区

请求出错了