繁体   English   中英

在java中读取文本文件

[英]Reading text file in java

在这里,我试图读取一个文本文件,其中每行只包含整数。例如:

1 
2 

3 
1

我编写了以下代码来读取文本文件。 代码如下所示。

 package fileread;
 import java.io.*;

 public class Main {


public static void main(String[] args) {
    // TODO code application logic here
    try{
        FileInputStream fstream=new FileInputStream("C:/Users/kiran/Desktop/text.txt");
        DataInputStream in=new DataInputStream (fstream);
        BufferedReader br=new BufferedReader(new InputStreamReader(in));
        String str;
        while((str=br.readLine())!=null){
            System.out.println(str);
        }
        in.close();
    }
    catch(Exception e){
        System.err.println(e);
    }
}

}

现在我想只检索那些重复并将其显示给用户的整数。 在这种情况下,我想显示“1”。

我怎样才能在Java中实现它?

您需要读取数组中的值,然后在该数组中查找重复的条目。

package fileread;
import java.io.*;
import java.util.HashSet;
import java.util.Set;

public class Main {


public static void main(String[] args) {
    Set<String> uniqueLines = new HashSet<String>();
    Set<String> duplicatedLines = new HashSet<String>();
    try{
        FileInputStream fstream=new FileInputStream("C:/Users/kiran/Desktop/text.txt");
        DataInputStream in=new DataInputStream (fstream);
        BufferedReader br=new BufferedReader(new InputStreamReader(in));
        String str;
        while((str=br.readLine())!=null){
            if (uniqueLines.contains(str)) {
                if (!duplicatedLines.contains(str)) {
                    duplicatedLines.add(str);
                    System.out.println(str);
                }
            } else {
                uniqueLines.add(str);
            }
        }
        in.close();
    }
    catch(Exception e){
        System.err.println(e);
    }
}

}

注意:确保您的输入在每行上没有尾随空格。 此外,请注意,当列表变长时,此实现不是特别适合内存。

完全读取文件,将行保存到您选择的数据结构(map(key = line,value = count),数组只有整数),枚举数据结构并打印其值大于1的值(如果值代表计数)。

或者即时:读取文件,添加条目/列表/数组,如果没有包含在set / list / array中,则打印输出行。

好吧,你可以使用一个带有10个插槽的数组,它们映射到0到9之间的数字。对于每一行,你检查那个数字是什么,并相应地增加数组中的值。 它会是这样的:

// Initialize the array
int[] numberArray = new int[10];
for (int i = 0 ; i < 10 ; i++) numberArray[i] = 0;

while((str=br.readLine())!=null){
   int number = Integer.parseInt(str);
   numberArray[number]++;
}

for (int i = 0 ; i < 10 ; i++) {\
   if (numberArray[i] > 1) System.out.println(i);
}

除了给定的答案之外,请确保将字符串转换为整数(数字)并捕获异常,以防来自文件的任何内容不是数字。 在这种情况下,我认为您可以安全地忽略该异常,因为它不相关,但检查输入数据是一个好习惯。

像这样的东西

package fileread;

import java.io.*;

import java.util.*;

public class Main {

public static void main(String[] args) {

    Hashtable ht = new Hashtable();

    try{
        FileInputStream fstream =
           new FileInputStream("C:/Users/kiran/Desktop/text.txt");

        DataInputStream in=new DataInputStream (fstream);

        BufferedReader br=new BufferedReader(new InputStreamReader(in));

        String str;

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

            String sproof = (String) ht.get(str.trim());
            if (sproof != null && sproof.equals("1")) {
                System.out.println(str);
            } else {
                ht.put(str.trim(), "1");
            } 
        }
        in.close();
    }
    catch(Exception e){
        System.err.println(e);
    }
}

}

首先,我将定义1个列表和1个整数集,如下所示:

ArrayList<Integer> intList = new ArrayList<Integer>();
Set<Integer> duplicateIntSet = new HashSet<Integer>(); //Set is used to avoid duplicates

然后,我会检查重复项并将'em'添加到各自的列表中,如下所示:

while((str=br.readLine())!=null){
    if(!str.isEmpty()) {
        Integer i = Integer.parseInt(str);

        if(intList.contains(i)) {
            duplicateIntSet.add(i);
        } else {
            intList.add(i);
        }
    }
}

我会用两套方法;

public static void main(String[] args) {
    Set<Integer> result = new HashSet<Integer>();
    Set<Integer> temp = new HashSet<Integer>();

    try{
        FileInputStream fstream=new FileInputStream("text.txt");
        DataInputStream in=new DataInputStream (fstream);
        BufferedReader br=new BufferedReader(new InputStreamReader(in));
        String str;
        while((str=br.readLine())!=null){
            if (!"".equals(str.trim())){
                try {
                    Integer strInt = new Integer(str.trim());
                    if(temp.contains(strInt)){
                        result.add(strInt);
                    } else {
                        temp.add(strInt);
                    }
                } catch (Exception e){
                    // usually NumberFormatException
                    System.err.println(e);
                }
            }
        }
        in.close();
    }
    catch(Exception e){
        System.err.println(e);
    }
    for(Integer resultVal : result){
        System.out.println(resultVal);
    }
}

或者,您也可以使用单个HashMap,其中HashMap.Key作为Integer,HashMap.Value作为该Integer的计数。 然后,如果您以后需要重构以查找单个事件的所有实例,那么您可以轻松地执行此操作。

    public static void main(String[] args) {
    Map<Integer, Integer> frequency = new HashMap<Integer, Integer>();

    try{
        FileInputStream fstream=new FileInputStream("text.txt");
        DataInputStream in=new DataInputStream (fstream);
        BufferedReader br=new BufferedReader(new InputStreamReader(in));
        String str;
        while((str=br.readLine())!=null){
            if (!"".equals(str.trim())){
                try {
                    Integer strInt = new Integer(str.trim());
                    int val = 1;
                    if(frequency.containsKey(strInt)){
                        val = frequency.get(strInt).intValue() + 1;
                    } 
                    frequency.put(strInt, val);
                } catch (Exception e){
                    // usually NumberFormatException
                    System.err.println(e);
                }
            }
        }
        in.close();
    }
    catch(Exception e){
        System.err.println(e);
    }
    // this is your method for more than 1
    for(Integer key : frequency.keySet()){
        if (frequency.get(key).intValue() > 1){
            System.out.println(key);
        }
    }
    // This shows the frequency of values in the file. 
    for(Integer key : frequency.keySet()){
        System.out.println(String.format("Value: %s, Freq: %s", key, frequency.get(key)));
    }
}

注意NumberFormatExceptions,根据你的情况,你可以在循环内或循环外处理它们。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM