读取src/step2/input/目录下的task.txt文件信息并输出到控制台,使用java代码将字符串learning practice写入到src/step2/output/目录下的output.txt,若文件目录不存在,则创建该目录。
时间: 2023-04-27 17:00:47 浏览: 181
从清单文件读取,批量复制文件到指定目录,如果目录不存在则创建目录.
3星 · 编辑精心推荐
可以使用以下代码实现:
1. 读取task.txt文件信息并输出到控制台:
```java
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class ReadFileDemo {
public static void main(String[] args) {
String filePath = "src/step2/input/task.txt";
File file = new File(filePath);
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
```
2. 将字符串learning practice写入到output.txt文件中:
```java
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class WriteFileDemo {
public static void main(String[] args) {
String dirPath = "src/step2/output";
String filePath = dirPath + "/output.txt";
String content = "learning practice";
File dir = new File(dirPath);
File file = new File(filePath);
BufferedWriter writer = null;
try {
if (!dir.exists()) {
dir.mkdirs();
}
if (!file.exists()) {
file.createNewFile();
}
writer = new BufferedWriter(new FileWriter(file));
writer.write(content);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (writer != null) {
writer.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
```
阅读全文