我编写了一个程序,该程序读取文本文件,删除请求的字符串,然后不使用该字符串重写它。该程序从终端接收三个参数:1)输入文件2)字符串3)输出文件。
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
class wordfilter {
public static void main(String[] args) {
Scanner scanner = new Scanner("");
Scanner conteggio = new Scanner("");
int numel = 0;
File file = new File(args[0]); // Argomento 0: il file
try {
conteggio = new Scanner(file);
}
catch (FileNotFoundException e) {
System.out.println("File non trovato");
}
while (conteggio.hasNext()) {
numel++;
conteggio.next();
}
conteggio.close();
String[] lettura = new String[numel];
int i = 0;
try {
scanner = new Scanner(file);
}
catch (FileNotFoundException e) {
System.out.println("File non trovato");
}
while (scanner.hasNextLine()) {
lettura[i] = scanner.next();
i++;
}
System.out.println("Contarighe -> " + numel);
for (i = 0; i < lettura.length; i++) {
System.out.println("Elemento " + i + " - > " + lettura[i]);
}
scanner.close();
String escludi = args[1]; // Argomento 1: il filtro
String[] filtrato = rimuovi(escludi, lettura);
if (args.length == 3) stampaSuFile(filtrato, args[2]);
}
public static String[] rimuovi(String esclusione, String[] input) {
String[] nuovoV;
String escludi = esclusione;
int dim = 0;
for (int i = 0; i < input.length; i++) {
if (!input[i].equals(escludi))
dim++;
}
nuovoV = new String[dim];
int j = 0;
for (int i = 0; i < input.length; i++) {
if (!input[i].equals(escludi)) {
nuovoV[j] = input[i];
j++;
}
;
}
return nuovoV;
}
public static void stampaSuFile(String[] out, String path) {
String closingstring = "";
File destinazione = new File(path);
try {
destinazione.createNewFile();
} catch (IOException e) {
System.out.println("Errore creazione file");
}
try {
FileWriter writer = new FileWriter(destinazione);
for (int i = 0; i < out.length; i++)
writer.write(out[i] + (i == (out.length-1) ? closingstring : " "));
writer.close();
System.out.println("Scrittura eseguita correttamente");
} catch (IOException e) {
System.out.println("Errore scrittura file");
}
}
}
在Windows上没问题,它运行正常。
在Linux上,当我写类似java wordfilter in.txt word out.txt
的内容时>
我知道
Exception in thread "main" java.util.NoSuchElementException at java.base/java.util.Scanner.throwFor(Scanner.java:937) at java.base/java.util.Scanner.next(Scanner.java:1478) at wordfilter.main(wordfilter.java:42)
有什么问题?是因为linux有所不同吗?
我编写了一个程序,该程序读取文本文件,删除请求的字符串,然后不使用该字符串重写它。该程序从终端接收三个参数:1)输入文件2)字符串3)...
输入文件在Linux上以换行符结尾。因此,还有另一行,但是它是空的。如果从输入中删除最后一个换行符,该程序将开始正常运行。