簡體   English   中英

使用Java從文本文件中讀取數據

[英]Read data from a text file using Java

我需要使用Java逐行讀取文本文件。 我使用FileInputStream available()方法來檢查和循環文件。 但是在讀取時,循環在最后一行之前的行之后終止。 ,如果文件有10行,則循環只讀取前9行。 使用的片段:

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

你不應該使用available() 它無法保證什么。 來自available()API文檔

返回可以從此輸入流中讀取(或跳過)的字節數的估計值 ,而不會被下一次調用此輸入流的方法阻塞。

你可能想要使用類似的東西

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

使用Scanner怎么樣? 我認為使用Scanner更容易

     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的更多信息

如果要逐行讀取,請使用BufferedReader 它有一個readLine()方法,它將該行作為String返回,如果已到達文件的末尾,則返回null。 所以你可以這樣做:

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

(請注意,此代碼不處理異常或關閉流等)

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();   
}

您可以從org.apache.commons.io.FileUtils嘗試FileUtils, 嘗試從這里下載jar

並且您可以使用以下方法:FileUtils.readFileToString(“yourFileName”);

希望它可以幫助你..

你的代碼跳過最后一行的原因是因為你把fis.available() > 0而不是fis.available() >= 0

Java 8中,您可以使用Files.lines輕松地將文本文件轉換為帶有流的字符串列表並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;
}
//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);
        }




    }
}

用戶掃描儀它應該工作

         Scanner scanner = new Scanner(file);
         while (scanner.hasNextLine()) {
           System.out.println(scanner.nextLine());
         }
         scanner.close(); 
public class ReadFileUsingFileInputStream {

/**
* @param args
*/
static int ch;

public static void main(String[] args) {
    File file = new File("C://text.txt");
    StringBuffer stringBuffer = new StringBuffer("");
    try {
        FileInputStream fileInputStream = new FileInputStream(file);
        try {
            while((ch = fileInputStream.read())!= -1){
                stringBuffer.append((char)ch);  
            }
        }
        catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    System.out.println("File contents :");
    System.out.println(stringBuffer);
    }
}

試試這只是在谷歌搜索一下

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());
    }
  }
}

嘗試使用像這樣的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();

是的,應該使用緩沖來獲得更好的性能。 使用BufferedReader OR byte []存儲臨時數據。

謝謝。

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);
    File file = new File("Path");

    FileReader reader = new FileReader(file);  

    while((ch=reader.read())!=-1)
    {
        System.out.print((char)ch);
    }

這對我有用

在JAVA中讀取文件的簡單代碼:

import java.io.*;

class ReadData
{
    public static void main(String args[])
    {
        FileReader fr = new FileReader(new File("<put your file path here>"));
        while(true)
        {
            int n=fr.read();
            if(n>-1)
            {
                char ch=(char)fr.read();
                System.out.print(ch);
            }
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM