java如何编写文字
在Java中编写文字
Java中处理文字主要通过字符串(String)类和相关方法实现。以下是常见的文字操作方式:
创建字符串
使用双引号直接声明字符串变量:
String text = "Hello World";
通过字符数组构建字符串:
char[] charArray = {'H','e','l','l','o'};
String text = new String(charArray);
字符串连接
使用加号运算符连接字符串:
String firstName = "John";
String lastName = "Doe";
String fullName = firstName + " " + lastName;
使用StringBuilder高效拼接(适用于大量拼接操作):
StringBuilder sb = new StringBuilder();
sb.append("Java");
sb.append(" ");
sb.append("Programming");
String result = sb.toString();
字符串格式化
使用String.format()方法:
String formatted = String.format("Name: %s, Age: %d", "Alice", 25);
从Java 15开始可以使用文本块(Text Blocks):
String html = """
<html>
<body>
<p>Hello World</p>
</body>
</html>
""";
文件读写文字
写入文本文件:
try (FileWriter writer = new FileWriter("output.txt")) {
writer.write("This is sample text");
}
读取文本文件:
try (BufferedReader reader = new BufferedReader(new FileReader("input.txt"))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
}
字符串处理常用方法
获取字符串长度:
int length = text.length();
字符串比较:
boolean isEqual = str1.equals(str2);
boolean isIgnoreCaseEqual = str1.equalsIgnoreCase(str2);
字符串分割:
String[] parts = "one,two,three".split(",");
字符串替换:
String replaced = text.replace("old", "new");
控制台输出文字
标准输出:
System.out.println("This will print with newline");
System.out.print("This won't add newline");
格式化输出:
System.out.printf("Formatted: %s %.2f", "Value", 3.14159);
国际化文字处理
使用ResourceBundle处理多语言:

ResourceBundle bundle = ResourceBundle.getBundle("Messages", locale);
String message = bundle.getString("greeting");
这些方法涵盖了Java中处理文字的基本操作,根据具体需求选择合适的方式。






