目标是从示例MonthTemps.txt中读取并写入两个文件(HotDays.txt,ColdNights.txt)。使用下面的代码我没有得到任何编译错误,但是假设要写入的两个文件仍然是空白的。我必须专门使用File和PrintWriter。
样品:
日高低
1 78 52
2 79 55
3 86 62
4 87 62
5 85 61
6 89 65
7 69 60
8 72 59
9 67 62
10 70 63
11 74 58
12 58 48
13 52 38
14 58 35
15 59 42
16 48 34
17 42 27
18 46 24
19 53 37
20 44 28
21 41 27
22 46 37
23 59 46
24 67 54
25 64 37
26 45 31
27 54 31
28 48 39
29 44 38
30 46 30
31 57 28
当前代码
import java.io.*;
import java.util.Scanner;
public class MJackson_Lab05 {
public static void main(String[] args) throws IOException {
//Declare values. I try to initialize at 0 because it gives an error.
int day, lowTemp, highTemp;
//Open sample
File MonthTemp = new File("MonthTemps.txt");
if (!MonthTemp.exists()){ //Check for existance
System.out.println("File not found!");
System.exit(1);
}
Scanner myInput = new Scanner(MonthTemp); //Scanner object
//Create new files
PrintWriter hotD = new PrintWriter("HotDays.txt");
PrintWriter coldN = new PrintWriter("ColdNights.txt");
//read data from scanner.
while (myInput.hasNext()){
day = myInput.nextInt();
lowTemp = myInput.nextInt();
highTemp = myInput.nextInt();
if (highTemp >= 80)
hotD.println(day + " " + highTemp + " " + lowTemp);
if (lowTemp < 30)
coldN.println(day + " " + highTemp + " " + lowTemp);
}
myInput.close();
hotD.close();
coldN.close();
System.exit(0);
}
}
答案 0 :(得分:1)
要从文件中读取,您需要:
InputStreamReader is = new InputStreamReader("path_of_your_file");
BufferReader br = new BufferReader(is);
然后使用while循环读取每一行,直到有一个有效输入:
br.readLine();
要在文件上书写,您必须使用oputputStreamReader("output_path")
代替inputStreamReader("input_path")
和write()
方法执行相同操作。
这是最简单的方式,当然这取决于你最后的purpouse
答案 1 :(得分:1)
你读取了所有数据,但没有存储,你应该在循环时放入条件
AppServiceProvider