java中读取文本文件

发布于 2024-12-24 22:13:57 字数 774 浏览 1 评论 0原文

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

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中实现这个?

Here I'm trying to read a text file which contains only integers.in every line.For eg:

1 
2 

3 
1

I wrote the following code to read the text file. Code as shown below.

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

}

Now I want to retrieve only those integers which repeated and display it to the user.
In this case i want to display "1".

How can I implement this in Java??

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

彩虹直至黑白 2024-12-31 22:13:57
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);
    }
}

}

注意:确保您的输入每行都没有尾随空格。另请注意,当列表变长时,此实现对内存不是特别友好。

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

}

Note: Make sure your input doesn't have trailing whitespace on each line. Also, note that when the list gets long, this implementation is not particularly memory friendly.

鲜肉鲜肉永远不皱 2024-12-31 22:13:57

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

You need to read the value in an array and then find duplicate entries in that array.

虫児飞 2024-12-31 22:13:57

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

或即时:读取文件,将条目添加到集合/列表/数组中(如果未包含在集合/列表/数组中),否则打印出行。

Read the file entirely, save the lines to a data structure of your choice (map(key=line, value=count), array if only integers), enumerate the data structure and print these whose value is greater than 1 (if the value represents the count).

or on the fly: read the file, add entry to a set/list/array, if not contained in set/list/array, else print out line.

浅浅淡淡 2024-12-31 22:13:57

那么,您可以使用具有 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);
}

Well, you can use an array with 10 slots which maps to a number from 0 to 9. For every line, you check what that number is and increment the value in the array accordingly. It would be something like this:

// 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);
}
孤芳又自赏 2024-12-31 22:13:57

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

In addition to the given answers, make sure you are converting your strings to integers (numbers) and catch the exception in case whatever comes from the file isn't a number. In this case I think you can safely ignore the exception because it's not relevant, but it's a good practice to check your input data.

月牙弯弯 2024-12-31 22:13:57

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

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

然后,我将检查重复项并将它们添加到相应的列表中,如下所示:

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

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

First off, I would define 1 list and 1 set of Integers, as below:

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

And then, I would check for duplicates and add 'em to respective lists, as below:

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

        if(intList.contains(i)) {
            duplicateIntSet.add(i);
        } else {
            intList.add(i);
        }
    }
}
柏林苍穹下 2024-12-31 22:13:57

像这样的东西

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

}

Something like this

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

}
夏九 2024-12-31 22:13:57

我会使用两组方法;

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,根据您的情况,您可以在循环内部或循环外部处理它们。

I would use the two set approach;

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

Alternately, you could also use a single HashMap with the HashMap.Key as the Integer and the HashMap.Value as count for that Integer.
Then if you later need to refactor to find all instances with a single occurrence then you can easily do that.

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

Be careful of NumberFormatExceptions, and depending on your situation, you can either handle them inside the loop, or outside the loop.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文