javaio流面试题
时间: 2023-10-24 09:09:45 浏览: 100
java 面试题
引的内容涉及到Java IO流的相关面试题。具体包括统计给定文件中给定字符串的出现次数的方法、将字符串写入文件的方法等。
1. 统计给定文件中给定字符串的出现次数的方法:
```java
public static int countWordInFile(String filename, String word) {
int counter = 0;
try (FileReader fr = new FileReader(filename)) {
try (BufferedReader br = new BufferedReader(fr)) {
String line = null;
while ((line = br.readLine()) != null) {
int index = -1;
while (line.length() >= word.length() && (index = line.indexOf(word)) >= 0) {
counter++;
line = line.substring(index + word.length());
}
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
return counter;
}
```
2. 将字符串写入文件的方法:
```java
public static void writeFile(String str) {
File file = new File("c:/test.txt");
PrintStream ps = null;
try {
OutputStream fos = new FileOutputStream(file);
ps = new PrintStream(fos);
ps.print(str);
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
ps.close();
}
}
```
阅读全文