我有一个我正在处理的程序,我想对txt文件执行以下操作
我现在所拥有的仅仅是它的骨头而没有任何肉,因为我正在努力开发算法 代码如下
import java.io.BufferedReader;
import java.io.FileNotFoundException; import java.io.FileReader;
import Java.util.Scanner;
public class Text {
public static void main(String [ ] args) {
try (Scanner s = new Scanner(new BufferedReader(new FileReader("Test.txt")))); {
while (s.hasNext()) {
System.out.println(s.next());
}
} catch (FileNotFoundException ex) {
System.out.println("unable to open file");
}
}
}
Text.txt看起来像
abc#.fruit.date
答案 0 :(得分:0)
您需要String
类方法replace
和Calendar.getInstace
。然后在那之后SimpleDateFormat
答案 1 :(得分:0)
这将执行正确的替换并将结果打印到System.out。文本文件的所有转换行都将在List<String> output
。
public static void main(String args[]) {
String fruits[] = {"Apple", "Orange", "Banana"}; //put whatever fruit values you want in here
List<String> output = new ArrayList<>();
try (Scanner s = new Scanner(new BufferedReader(new FileReader("Test.txt")))) {
while (s.hasNext()) {
String line = s.nextLine();
line = line.replaceAll("#", String.valueOf(randomNumber(1, 9)));
line = line.replaceAll("fruit", fruits[randomNumber(0, fruits.length-1)]);
line = line.replaceAll("date", new SimpleDateFormat("YYYYMMDD").format(new Date()));
output.add(line);
}
} catch (FileNotFoundException ex) {
System.out.println("Unable to open file.");
}
for (String line : output) {
System.out.println(line);
}
}
private static int randomNumber(int min, int max) {
Random rand = new Random();
return rand.nextInt((max - min) + 1) + min;
}
输入:
abc#.fruit.date
示例输出:
abc7.Apple.201508223