java 写入到.txt文件

直接上代码

String fileName =new SimpleDateFormat("yyyyMMdd").format(new date())+".txt";
File file = null;
FileWriter fw = null;
try {
	file = new File(PropKit.get("trajectoryPath")+fileName);
	if (!file.exists()) {
		file.createNewFile();
	}
	fw = new FileWriter(file);
	fw.write("要写入的内容......"+"\r\n");
	fw.flush();
	fw.close();
} catch (IOException e) {
	e.printStackTrace();
}

总共三步,首先创建文件,然后用流将内容写入文件,最后关闭流

  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是一个Java程序,可以实现你所需要的功能: ```java import java.io.*; import java.util.*; public class FileStats { public static void main(String[] args) { String inputFile = "abc.txt"; String outputFile = "result.txt"; try (BufferedReader reader = new BufferedReader(new FileReader(inputFile)); BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile))) { int wordCount = 0; int lineCount = 0; Map<Character, Integer> charCounts = new HashMap<>(); String line; while ((line = reader.readLine()) != null) { lineCount++; // Split the line into words String[] words = line.split("[^a-zA-Z]+"); for (String word : words) { if (!word.isEmpty()) { wordCount++; // Count the characters in the word for (char c : word.toCharArray()) { charCounts.put(c, charCounts.getOrDefault(c, 0) + 1); } } } } // Write the results to the output file writer.write(String.format("Word count: %d\n", wordCount)); writer.write(String.format("Line count: %d\n", lineCount)); writer.write("Character counts:\n"); for (Map.Entry<Character, Integer> entry : charCounts.entrySet()) { char c = entry.getKey(); int count = entry.getValue(); double percent = ((double) count / wordCount) * 100; writer.write(String.format("%c: %d (%.2f%%)\n", c, count, percent)); } System.out.println("Results written to " + outputFile); } catch (IOException e) { e.printStackTrace(); } } } ``` 该程序使用了Java文件输入输出库,以及Java的集合框架。它的思路是先读取输入文件的每一行,然后将每一行拆分成单词,再统计单词数和每个字符出现的次数。最后将结果写入输出文件。 你只需要将程序中的 `abc.txt` 和 `result.txt` 替换成你自己的文件名,即可使用。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值