java - 在 txt 文件中查找整数和浮点数
问题描述
我有一个简单的代码问题,不知道该怎么做;我有 3 个 txt 文件。第一个 txt 文件如下所示:
1 2 3 4 5 4.5 4,6 6.8 8,9
1 3 4 5 8 9,2 6,3 6,7 8.9
我想从这个 txt 文件中读取数字并将整数保存到一个 txt 文件并浮动到另一个。
解决方案
您可以通过以下简单步骤来做到这一点:
- 当您读取一行时,将其拆分为空格并获取一组标记。
- 在处理每个令牌时,
- 修剪任何前导和尾随空格,然后替换
,
为.
- 首先检查令牌是否可以解析为
int
. 如果是,请将其写入outInt
(整数编写器)。否则,检查令牌是否可以解析为float
. 如果是,请将其写入outFloat
(浮点数的编写器)。否则,忽略它。
- 修剪任何前导和尾随空格,然后替换
演示:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws FileNotFoundException, IOException {
BufferedReader in = new BufferedReader(new FileReader("t.txt"));
BufferedWriter outInt = new BufferedWriter(new FileWriter("t2.txt"));
BufferedWriter outFloat = new BufferedWriter(new FileWriter("t3.txt"));
String line = "";
while ((line = in.readLine()) != null) {// Read until EOF is reached
// Split the line on whitespace and get an array of tokens
String[] tokens = line.split("\\s+");
// Process each token
for (String s : tokens) {
// Trim any leading and trailing whitespace and then replace , with .
s = s.trim().replace(',', '.');
// First check if the token can be parsed into an int
try {
Integer.parseInt(s);
// If yes, write it into outInt
outInt.write(s + " ");
} catch (NumberFormatException e) {
// Otherwise, check if token can be parsed into float
try {
Float.parseFloat(s);
// If yes, write it into outFloat
outFloat.write(s + " ");
} catch (NumberFormatException ex) {
// Otherwise, ignore it
}
}
}
}
in.close();
outInt.close();
outFloat.close();
}
}
推荐阅读
- ios - 如何在 iOS 中通过 musicxml 绘制乐谱?
- facebook-graph-api - Instagram 业务发现 API 分页令牌不起作用?
- java - 通过重新创建模式将领域迁移到特定版本的数据库
- hippocms - 如何在 hippo cms 中创建浏览器级别的图像缓存。还建议我如何在我的本地做到这一点
- c - Openssl RSA在C中加密和解密
- ios - Youtube Player 继续在使用 react native 构建的 IOS 9.3 中进行缓冲
- python - Pandas 错误 - “ValueError:标签 ['attributes'] 不包含在轴中”
- jquery - 使用 jquery 拖放电子邮件模板生成器
- android - 当未满足强制要求时,是否忽略 Enote Android 作业中的执行窗口结束
- kubernetes - 服务账号存在,但出现“找不到服务账号kube-lego/kube-lego2-kube-lego,创建服务账号后重试”的错误