[英]Java text file remove doubles from four column text file
我必须编写代码以获取包含整数和双精度数的文本文件,并在文件中打印双精度数,并在另一个文件中打印整数。 文本文件的格式如下:
double int int int
double int int int
...
double int int int
它保存在"raw.txt"
文件中。
输出应如下所示:
int int int
int int int
...
int int int
到目前为止,这是我尝试过的:
import java.io.*;
import java.util.*;
public class DATA {
public static void main(String[] args) throws FileNotFoundException {
PrintWriter writer = new PrintWriter(new File("sorted.txt"));
Scanner reader = new Scanner(new File("raw.txt"));
int temp = 0, count = 1;
while (reader.hasNext()) {
try {
temp = reader.nextInt();
}
catch (InputMismatchException e) {
reader.nextLine();
temp = (int) reader.nextDouble();
}
writer.print(temp);
if (count % 4 == 0)
writer.println();
count++;
}
writer.close();
reader.close();
}
}
当前代码将引发InputMismatchException
。 非常感谢所有帮助。
根据您提供的代码,您只想分割文件,而不关心double
和int
值本身。 因此,您可以将文件作为普通文本文件处理,并用分隔的空白字符分隔值。
该代码段对raw.txt
文件的格式进行了一些假设,并且未进行优化。 因此,根据您的需求进行修改应该是一件容易的事。
public static void main(String[] args) throws IOException {
List<String> rawLines = Files.readAllLines(Paths.get("raw.txt"));
try (Writer intWriter = Files.newBufferedWriter(
Paths.get("int_values.txt"),
StandardOpenOption.CREATE_NEW);
Writer doubleWriter = Files.newBufferedWriter(
Paths.get("double_values.txt"),
StandardOpenOption.CREATE_NEW)) {
for (String line : rawLines) {
// the split might need to be amended if the values
// are not separated by a single blank
String[] values = line.split(" ");
// to be amended if there are not alway four values in a row
if (values.length != 4) {
continue;
}
doubleWriter.write(values[0]);
doubleWriter.write(System.lineSeparator());
intWriter.write(values[1]);
intWriter.write(' ');
intWriter.write(values[2]);
intWriter.write(' ');
intWriter.write(values[3]);
intWriter.write(' ');
intWriter.write(System.lineSeparator());
}
}
}
可以抛出InputMismatchException
因为它是整数Integer Double
最好将一个零件读为一个字符串然后决定
在决定时,将引发NumberFormatException
,可以捕获该异常
在下面的代码中,有两个编写器可以按您的意愿分开,可能看起来比这段代码更好
我已经纠正了您写的文件。 我还没有测试过,但是我真的认为如果你做writer.print(temp);
,它将放置所有没有空格的整数,这是没有用的。
试试此代码,但未经测试
import java.io.*;
import java.util.*;
public class DATA {
public static void main(String[] args) throws FileNotFoundException {
PrintWriter writerInt = new PrintWriter(new File("sortedInt.txt"));
PrintWriter writerDou = new PrintWriter(new File("sortedDou.txt"));
Scanner reader = new Scanner(new File("raw.txt"));
int temp = 0, countInt = 1, countDou = 1;
while (reader.hasNext()) {
String next = reader.next();
try{
temp=Integer.parseInt(next);
writerInt.print(temp+" ");
if (countInt % 4 == 0)
writerInt.println();
countInt++;
}catch(NumberFormatException e){
try{
writerDou.print(Double.parseDouble(next)+" ");
if (countDou % 4 == 0)
writerDou.println();
countDou++;
}catch(NumberFormatException f){
System.out.println("Not a number");
}
}
}
writerInt.close();
writerDou.close();
reader.close();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.