[英]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.