Java如何读取字符串
时间: 2024-10-14 07:10:10 浏览: 37
在Java中,读取字符串通常涉及到创建String对象并从各种数据源获取字符序列。这里有一些常见的方法:
1. **直接赋值**:如果你有一个字符串字面量,可以直接创建它:
```java
String str = "Hello, World!";
```
2. **使用`new String()`构造函数**:你可以将其他字符数组、byte数组或InputStream转换成字符串:
```java
byte[] bytes = {'H', 'e', 'l', 'l', 'o'};
String strFromBytes = new String(bytes);
// 或者从文件流
FileInputStream fis = new FileInputStream("file.txt");
byte[] fileBytes = new byte[(int) fis.getChannel().size()];
fis.read(fileBytes);
String strFromFile = new String(fileBytes, StandardCharsets.UTF_8);
```
3. **使用`Scanner`类**:如果你想从控制台输入或者文件中逐行读取,可以使用Scanner类:
```java
Scanner scanner = new Scanner(System.in);
System.out.print("请输入字符串:");
String inputStr = scanner.nextLine();
```
4. **使用`BufferedReader`**:对于文本文件读取,可以使用BufferedReader配合InputStreamReader:
```java
BufferedReader br = new BufferedReader(new FileReader("file.txt"));
String line;
while ((line = br.readLine()) != null) {
String content = line; // 这里content就是当前读取的一行
}
```
阅读全文