9

Java を使用してテキスト ファイルを 1 行ずつ読み取る必要があります。available()のメソッドを使用FileInputStreamして、ファイルをチェックしてループします。ただし、読み取り中は、最後の行の前の行の後でループが終了します。つまり、ファイルに 10 行ある場合、ループは最初の 9 行だけを読み取ります。使用されるスニペット:

while(fis.available() > 0)
{
    char c = (char)fis.read();
    .....
    .....
}
4

16 に答える 16

14

を使用しないでくださいavailable()。それは今までに何の保証も与えません。のAPI ドキュメントからavailable():

この入力ストリームのメソッドの次の呼び出しによってブロックされることなく、この入力ストリームから読み取る (またはスキップする) ことができる推定バイト数を返します。

あなたはおそらく次のようなものを使いたいでしょう

try {
    BufferedReader in = new BufferedReader(new FileReader("infilename"));
    String str;
    while ((str = in.readLine()) != null)
        process(str);
    in.close();
} catch (IOException e) {
}

( http://www.exampledepot.com/egs/java.io/ReadLinesFromFile.htmlから取得)

于 2010-05-19T09:09:33.860 に答える
11

スキャナーを使ってみませんか?スキャナーの方が使いやすいと思います

     private static void readFile(String fileName) {
       try {
         File file = new File(fileName);
         Scanner scanner = new Scanner(file);
         while (scanner.hasNextLine()) {
           System.out.println(scanner.nextLine());
         }
         scanner.close();
       } catch (FileNotFoundException e) {
         e.printStackTrace();
       }
     }

Java IO の詳細については、こちらをご覧ください

于 2010-05-19T09:09:19.773 に答える
3

行ごとに読みたい場合は、BufferedReader. 行をreadLine()文字列として返すメソッド、またはファイルの終わりに達した場合は null を返すメソッドがあります。したがって、次のようなことができます。

BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
String line;
while ((line = reader.readLine()) != null) {
 // Do something with line
}

(このコードは例外を処理したり、ストリームを閉じたりしないことに注意してください)

于 2010-05-19T09:09:47.533 に答える
3
String file = "/path/to/your/file.txt";

try {

    BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
    String line;
    // Uncomment the line below if you want to skip the fist line (e.g if headers)
    // line = br.readLine();

    while ((line = br.readLine()) != null) {

        // do something with line

    }
    br.close();

} catch (IOException e) {
    System.out.println("ERROR: unable to read file " + file);
    e.printStackTrace();   
}
于 2010-05-19T09:14:50.540 に答える
2

org.apache.commons.io.FileUtils から FileUtils を試すことができます。ここから jar をダウンロードしてみてください。

次のメソッドを使用できます: FileUtils.readFileToString("yourFileName");

それがあなたを助けることを願っています..

于 2011-05-11T10:19:20.880 に答える
1

Java 8 ではFiles.linesandを使用して、ストリームを含む文字列のリストにテキスト ファイルを簡単に変換できますcollect

private List<String> loadFile() {
    URI uri = null;
    try {
        uri = ClassLoader.getSystemResource("example.txt").toURI();
    } catch (URISyntaxException e) {
        LOGGER.error("Failed to load file.", e);
    }
    List<String> list = null;
    try (Stream<String> lines = Files.lines(Paths.get(uri))) {
        list = lines.collect(Collectors.toList());
    } catch (IOException e) {
        LOGGER.error("Failed to load file.", e);
    }
    return list;
}
于 2015-05-04T10:57:08.967 に答える
1

コードが最後の行をスキップした理由は、fis.available() > 0代わりにfis.available() >= 0

于 2014-11-24T01:25:52.937 に答える
1
//The way that I read integer numbers from a file is...

import java.util.*;
import java.io.*;

public class Practice
{
    public static void main(String [] args) throws IOException
    {
        Scanner input = new Scanner(new File("cards.txt"));

        int times = input.nextInt();

        for(int i = 0; i < times; i++)
        {
            int numbersFromFile = input.nextInt();
            System.out.println(numbersFromFile);
        }




    }
}
于 2017-10-14T17:25:24.077 に答える
0

はい、パフォーマンスを向上させるためにバッファリングを使用する必要があります。BufferedReader OR byte[] を使用して、一時データを保存します。

ありがとう。

于 2010-05-19T11:28:13.987 に答える
0
public class FilesStrings {

public static void main(String[] args) throws FileNotFoundException, IOException {
    FileInputStream fis = new FileInputStream("input.txt");
    InputStreamReader input = new InputStreamReader(fis);
    BufferedReader br = new BufferedReader(input);
    String data;
    String result = new String();

    while ((data = br.readLine()) != null) {
        result = result.concat(data + " ");
    }

    System.out.println(result);
于 2015-08-05T13:36:40.823 に答える
0

Google で少し検索してみてください

import java.io.*;
class FileRead 
{
   public static void main(String args[])
  {
      try{
    // Open the file that is the first 
    // command line parameter
    FileInputStream fstream = new FileInputStream("textfile.txt");
    // Get the object of DataInputStream
    DataInputStream in = new DataInputStream(fstream);
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
    String strLine;
    //Read File Line By Line
    while ((strLine = br.readLine()) != null)   {
      // Print the content on the console
      System.out.println (strLine);
    }
    //Close the input stream
    in.close();
    }catch (Exception e){//Catch exception if any
      System.err.println("Error: " + e.getMessage());
    }
  }
}
于 2010-05-19T09:10:11.150 に答える
0

このようにjava.io.BufferedReaderを使用してみてください。

java.io.BufferedReader br = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(fileName)));
String line = null;
while ((line = br.readLine()) != null){
//Process the line
}
br.close();
于 2010-05-19T09:11:51.023 に答える
0

ユーザースキャナーは動作するはずです

         Scanner scanner = new Scanner(file);
         while (scanner.hasNextLine()) {
           System.out.println(scanner.nextLine());
         }
         scanner.close(); 
于 2013-07-30T15:22:47.427 に答える