私は初心者であり、助けが必要です。私はテキストファイルを1行ずつ配列にスキャンしようとしていますが、1行は省略しています。私のテキストファイルには、私は彼が彼女はそれは私がこれをスキャンし、置く方法を作成したいテキストファイルを配列にスキャンして指定された1行を省略する
ある
ある
であるあなたが
ある
だ
です(メソッドのパラメータとしてStringを入力することによって選択される)1行を例外として、配列に要素を追加します。その後、元のテキストファイルを消去し、作成された配列をその行(削除された行は1つもありません)に出力します。申し訳ありませんが、私は説明を吸う。
私はこれを試してみました:
public static void deleteLine(String name, String line) throws IOException {
String sc = System.getProperty("user.dir") + new File("").separator;
FileReader fr = new FileReader(sc + name + ".txt");
Scanner scan = new Scanner(fr);
int n = countLines(name); // a well working method returning the number if lines in the file (here 5)
String[] listArray = new String[n-1];
for (int i = 0; i < n-1; i++) {
if (scan.hasNextLine() && !scan.nextLine().equals(line))
listArray[i] = scan.nextLine();
else if (scan.hasNextLine() && scan.nextLine().equals(line))
i--;
else continue;
}
PrintWriter print = new PrintWriter(sc + name + ".txt");
print.write("");
for (int i = 0; i < n-2; i++) {
print.write(listArray[i] + "\n");
}
print.close()
}
私は、私が入力したときにエラーが見つかりません「ライン」を取得:deleteLine(「all_names」、「あなたがいる」という。)(all_namesは、ファイルの名前です)。私は問題がfor-loopにあると確信していますが、なぜこれがうまくいかないのか分かりません。 :(
//このコードは、結局働い//
を解決しました。答えてくれてありがとう!
public static void deleteLine(String name, String line) throws IOException{
String sc = System.getProperty("user.dir") + new File("").separator;
FileReader fr = null;
fr = new FileReader(sc+name+".txt");
Scanner scan = new Scanner(fr);
int n = LineCounter(name);
String[] listArray = new String[n-1];
for (int i = 0; i < n-1; i++) {
if (scan.hasNextLine()) {
String nextLine = scan.nextLine();
if (!nextLine.equals(line)) {
listArray[i] = nextLine;
}
else i--;
}
}
PrintWriter print = new PrintWriter(sc+name+".txt");
print.write("");
for(int i=0;i<n-1;i++){
print.write(listArray[i]+System.lineSeparator());
}
print.close();
}
コード規約上の注意:Javaメソッドでは、小文字で始まります。 –