[英]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.