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??
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.
You need to read the value in an array and then find duplicate entries in that array.
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.
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);
}
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.
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);
}
}
}
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);
}
}
}
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.
Related
I want to change the form of a given graph. The graph is in the form userID, number of followers, follower1, follower2, ..followerN, delimiter '---', userID2, ...etc.
I have to replace the followers with place values from a second file of the form
ID1 place1
ID2 place2
....
by matching the IDs.
Thus, I want to check if the followers id each time exists in a set.
Both my graph and the set where I seek for the follower ids are huge.
Is there a more efficient way than the one I give you below?
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.util.*;
public class Changer {
public static void main(String[] args) {
Set set = new HashSet();
int[][] users=new int[61578415][];
try{
FileInputStream fstream2 = new FileInputStream(args[0]);
DataInputStream in2 = new DataInputStream(fstream2);
BufferedReader br2 = new BufferedReader(new InputStreamReader(in2));
String strLine2;
while ((strLine2 = br2.readLine()) != null) {
set.add(strLine2);
}
in2.close();
fstream2.close();}
catch (Exception e){
System.err.println("Error: " + e.getMessage()+"!\n"+e.toString()+"!\n");
e.printStackTrace();
System.exit(-1);
}
try{
FileInputStream fstream = new FileInputStream("InputGraph.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
int flag=0;
int pos=0;
FileWriter fstream3 = new FileWriter("OutputGraph.txt");
BufferedWriter out = new BufferedWriter(fstream3);
int currentUser=0,counter=0;
int theNum=0;
while ((strLine = br.readLine()) != null) {
if(strLine.equals("---")){
if(counter!=pos){
System.out.println("Error reading graph");
System.out.println("For:"+currentUser);
System.exit(-1);
}
flag=0;
pos=0;
continue;
}
theNum=Integer.parseInt(strLine);
if (flag==0){
out.write("---"+"\n");
out.write(""+theNum);
out.write("\n");
currentUser=theNum;
flag+=1;
}
else if (flag==1){
counter=theNum;
users[currentUser]=new int [counter];
flag+=1;
out.write(""+theNum+"\n");
}
else{
users[currentUser][pos]=theNum;
++pos;
Iterator it = set.iterator();
while (it.hasNext()) {
Object element = it.next();
String[] arr = (String.valueOf(element)).split(" ");
if (Integer.parseInt(arr[0])==theNum)
{theNum=Integer.parseInt(arr[1]);break;}
}
out.write(""+theNum);
out.write("\n");
}
}
in.close();
out.close();
}catch (Exception e){
System.err.println("Error: " + e.getMessage());
}
System.out.println("Graph has been read");
System.gc();
System.gc();
System.out.println("Finished");
}
}
It would be more efficient to do the for loop over intersection inside, so that you don't split and parse so much:
Iterator it = set.iterator();
while (it.hasNext()) {
Object element = it.next();
String[] arr = (String.valueOf(element)).split(" ");
int arr0 = Integer.parseInt(arr[0]);
int arr1 = Integer.parseInt(arr[1]);
for (int integer : intersection) {
if (arr0 == integer) {
out.write(integer + " " + arr1 + "\n");
}
}
}
But this changes the order the write will be called in.
However I suspect you might benefit from loading it in to (or just replacing with) a HashMap or SparseArray. It's just hard to tell give then info you have given.
For Integer detection, you can use the comparation with instanceof , but you must use objects and not primitives, e.g:
Integer a=Integer.parseInt("12345");
if(a instanceof Integer){
System.out.println("We have an integer !");
}
Another way for Integer detection is to override the equals method.
My assignment is as following Create Java program that reads from file create one person Object per line and stores object in a collection write the object out sorted by last name. this is what I have so far it compiles just fine but it doesn't print out anything. This is what I have so far
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class FileTester {
public static void main(String[] args) {
File testFile;
Scanner fileScanner;
try {
testFile = new File("sample.txt");
fileScanner = new Scanner(testFile);
fileScanner.useDelimiter(",");
while (fileScanner.hasNext()) {
System.out.println(fileScanner.next());
}
fileScanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
If it is a text file, please use BufferedReader. Then use String#split() to get the data. Instantiate as necessary.
BufferedReader reader = new BufferedReader(...);
String line = null;
while( (line = reader.readLine()) != null){
// magic
}
I do not know what you want to do. But this program take a file called "sample.txt" and divide in tokens this. For example if in the txt is "carlos,jose,herrera,matos" you program out
carlos
jose
herrera
matos
now if you want to sort this, you must create a class Person and implement the Comparable
Try this,
BufferedReader bufferedReader = new BufferedReader(new FileReader(new File(fileName)));
String content = null;
while((content = bufferedReader.readLine()) != null)
{
String[] details = content.split(",");
int i = 1;
for(String value : details)
{
switch(i)
{
case 1:
{
System.out.println("Name : "+value);
i=2;
break;
}
case 2:
{
System.out.println("Address : "+value);
i=3;
break;
}
case 3:
{
System.out.println("Number : "+value);
i = 1;
break;
}
}
}
}
I'm new at java I would like to know how to read a .txt file and then put every single line in an array cell.
.txt file must be formatted as shown:
car //goes in array[0]
boat //goes in array[1]
ship //goes in array[2]
airplane //goes in array[3]
//...and so on..
I've already tried to create a ReadFile class implemented in this way:
import java.io.*;
import java.util.*;
public class ReadFile {
private Scanner x;
public void open(){
try{
x = new Scanner(new File("time_table_data.txt"));
}catch(Exception e){
System.out.println("Could Not Create The File");
}
}
public String read(){
String s = "";
while(x.hasNext()){
String a = x.next();
s = a.format("%s\n",a);
}
return s;
}
public void close(){
x.close();
}
}
The problem is that you don't know how many words there are coming. To solve that, you could use an ArrayList.
List<String> entries = new ArrayList<String>();
while (scanner.hasNext())
{
entries.add(scanner.nextLine());
}
System.out.println(entries);
Access them using the get(int index) method:
String test = entries.get(0); // This will be "car"
if you're willing to use Apache Commons IO then you can do this really easy:
import org.apache.commons.io.FileUtils;
String[] linesArr = new String[0];
List<String> lines = FileUtils.readLines(new File("FILE_NAME.txt"));
if (lines != null) {
linesArr = lines.toArray(linesArr);
}
Just do:
List<String> lines = new ArrayList<String>();
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
while ((line = br.readLine()) != null) {
lines.add(line); // Add line to list
}
} // Try-with-resources closes reader
You don't need the scanner or anything else fancy when you just looking for whole lines.
If you really need an array not a list at the end you can just read out the array from the final List.
Make a method that reads all data from file and stores in a List as follows.
public ArrayList<String> fileRead(String fileName){
File f;
String s;
FileReader fr = null;
BufferedReader br = null;
ArrayList<String> sl = new ArrayList<String>();
try {
f = new File(fileName);
fr = new FileReader(f);
br = new BufferedReader(fr);
while((s=br.readLine())!=null){
sl.add(s);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
if(br!=null)
br.close();
if(fr!=null)
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sl;
}
I have a file that contain 100 line
each line contain one tag
I need to obtain the tag value given its rank which is the "id" of TagVertex Class
public abstract class Vertex <T>{
String vertexId ;// example Tag1
T vertexValue ;
public abstract T computeVertexValue();
}
public class TagVertex extends Vertex<String> {
#Override
public String computeVertexValue() {
// How to get the String from my file?
return null;
}
T try this but it doesnt work
public static void main(String args[]) {
File source //
int i=90;
int j=0;
String s = null;
try {
Scanner scanner = new Scanner(source);
while (scanner.hasNextLine()) {
if (j==i) s= scanner.nextLine();
else j++;
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(s);
}}
Although there is a way to skip characters with BufferedReader, I don't think there's is a built-in way to skip whole lines.
BufferedReader bf = new BufferedReader(new FileReader("MyFile.txt"));
for(int i = 1; i < myVertex.vertexId; i++){
bf.readLine();
}
String n = bf.readLine();
if(n != null){
System.out.println(n);
}
I think there may be a better idea though.
This is command u can use to read from file:
BufferedReader bf = new BufferedReader(new FileReader("filename"));
This will read the file to the buffer.
Now, for reading each line u should use a while loop and read each line into string.
Like:
String str;
while((str = bf.readLine()) != null){
//handle each line untill the end of file which will be null and quit the loop
}
I have been making a little program that needs to read a list of golf courses that could be changeing and needs to be called when ever. Here is the code:
public class Courses {
public String[] courselist;
public void loadCourses() throws IOException{
int count = 0;
int counter = 0;
File f = new File("src//courses//courses.txt");
BufferedReader reader = new BufferedReader(new FileReader(f));
while(count<1){
String s = reader.readLine();
if(s.equalsIgnoreCase("*stop*")){
reader.close();
count = 5;
}else{
courselist[counter] = s;
counter++;
}
s = "";
}
}
}
And now this is what is in the txt file.
RiverChase
Steward Peninsula
Lake Park
Coyote Ridge
*stop*
Now when ever i start to run the program because i call the method instantly it gives me a throw exeption and it is because of the array. And i need to stay and array because i use it in a JComboBox. If you can help or fix the problem. Most likely im just doing it wrong, im a noob. Just help. Thanks in advance.
I know all the file reader and stuff works because it prints out to the system correct, i just need help writing it to the array repetedly.
You should initialize your array before using it
public static final MAX_SIZE = 100;
public String[] courselist = new String[MAX_SIZE];
Change your code to assign a new array during loadCourses(), and add a call to loadCourses() to your constructor:
public class Courses {
public String[] courselist;
public Courses() throws IOException { // <-- Added constructor
loadCourses(); // <-- Added call to loadCourses
}
public void loadCourses() throws IOException {
int count = 0;
int counter = 0;
File f = new File("src//courses//courses.txt");
BufferedReader reader = new BufferedReader(new FileReader(f));
List<String> courses = new ArrayList<String>(); // <-- A List can grow
while(true){
String s = reader.readLine();
if (s.equalsIgnoreCase("*stop*")){
break;
}
courses.add(s);
}
courseList = courses.toArray(new String[0]); // <-- assign it here
}
}
This ensures that when you create an instance, it starts out life with the array initialised. Not only will you not get an error, but the data will always be correct (unlike other answers that simply create an empty (ie useless) array.
Note that this code will work with any number of course names in the file (not just 5).
You'd better create a List that is easier to manipulate and convert it as an array at the end of the process :
List<String> list = new ArrayList<String>();
String [] array = list.toArray(new String [] {});
Here is a possible implementation of the loading using a List :
public static String [] loadCourses() throws IOException {
File f = new File("src//courses.txt");
BufferedReader reader = new BufferedReader(new FileReader(f));
List<String> courses = new ArrayList<String>();
while (true){
String s = reader.readLine();
if (s == null || s.trim().equalsIgnoreCase("*stop*")){
break;
} else{
courses.add(s);
}
}
return courses.toArray(new String [] {});
}
Also why use a stop keyword ? You could simply stop the process when you reach the end of the file (when s is null).
Here some example, without using the *stop*:
public class ReadFile {
public static void main(String[] args) {
BufferedReader reader = null;
List<String> coursesList = new ArrayList<>();
String[] courses;
try {
File file = new File("courses.txt");
reader = new BufferedReader(new FileReader(file));
String readLine;
do {
readLine = reader.readLine();
if(readLine == null)
break;
coursesList.add(readLine);
} while (true);
} catch (IOException ex) {
Logger.getLogger(ReadFile.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
reader.close();
} catch (IOException ex) {
Logger.getLogger(ReadFile.class.getName()).log(Level.SEVERE, null, ex);
}
}
courses = coursesList.toArray(new String[coursesList.size()]);
for(int i = 0; i < courses.length; i++) {
System.out.println(courses[i]);
}
}
}