Read lines from a file and compare their equality [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I need to write a progam to read a text file and compare its lines. I want to store them in an array, but I do not how to do this and how to compare, if they are equal.
package pantoum;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Pantoum {
public static void main(String[] args) throws FileNotFoundException {
//get filename input from user
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the full file name: ");
String fileName = keyboard.nextLine();
File inputFile = new File(fileName);
if (inputFile.exists()){
//create scanner to read file
Scanner input = new Scanner(inputFile);
//while (input.hasNext());{
String title = input.next();
System.out.println(title);
}
else
{
System.out.println("Sorry, that file does not exist.");
}
}
}

i personally prefer to use buffered reader when it comes to reading from a text file.
boolean equal=false;
String lines[] =new [10];
// or however long the array needs to be.
int count=0;
BufferedReader infile = new BufferedReader(new FileReader("<Name of file>"));
do {
lines[count] = infile.readLine();
count++;
} while (lines[count] != null);
for(int i=0;i<lines.length();i++) {
for(int j = i+1; j<lines.length()-1;j++){
if(lines[i].equals(lines[j])){
equal=true;
system.out.print(lines[i]+" and "+lines[j]+" are equal");
}}}
if(!equal){
system.out.print("Sorry your text did not equal any text from the text file");
}
i hope this helped and i hope i have explained everything well enough for you to understand, if not feel free to ask.

I personally would read each line into a String[] position and then in a loop check if String[i].equals(String[j]). If you need a rough idea how to code this let me know.

You can just use scanner's nextLine() method to get an entire line and then compare them using String.equals()
something like
String line1 = input.nextLine();
String line2 = input.nextLine();
if(line1.equals(line2){
doStuff();
}

Related

How would I write this code to make it read a file that has an unknown amount of lines? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class Process_TCPProbe_dm{
public static void main(String[] args) throws IOException {
//Extracting the port numbers from the file names passed in the arguments
String portNumber1 = args[1].substring(9, 14);
String portNumber2 = args[2].substring(9, 14);
String portNumber3 = args[3].substring(9, 14);
int i = 0;
Scanner s = new Scanner(new FileReader(args[0]));
//Initialising array of contents with length equals to number of lines in the input file
String[] contents = new String[18];
while(true)
{
if (i == 18)
break;//Skipping the last line of the file
//Replaces the whitespace with comma and stores in the string array
contents[i] = s.nextLine().replace(" ", ",");
i++;
}
BufferedWriter bw1 = new BufferedWriter(new FileWriter(args[1]));
BufferedWriter bw2 = new BufferedWriter(new FileWriter(args[2]));
BufferedWriter bw3 = new BufferedWriter(new FileWriter(args[3]));
//Iterating the array of contents using a for each loop
for(String each:contents)
{
//Writing the string to the corresponding file which matches with the portNumber
//along with a new line
if (each.contains(portNumber1))
{
bw1.write(each);
bw1.newLine();
}
else if(each.contains(portNumber2))
{
bw2.write(each);
bw2.newLine();
}
else if(each.contains(portNumber3))
{
bw3.write(each);
bw3.newLine();
}
}
//This is necessary to finally output the text from the buffer to the corresponding file
bw1.flush();
bw2.flush();
bw3.flush();
//Closing all the file reading and writing handles
bw1.close();
bw2.close();
bw3.close();
s.close();
}
}
Here is my code, however, it only reads a file the size of 19 lines. I know i could use an ArrayList, but I'm not exactly sure how to go about it. I hope my question makes sense. If it'll help you understand better ill put the purpose of the code below.
This image is of the instructions for what the code is written for. It might just be extra information, but I put it here in case it'll better help to explain my question.
Just replace your array with Array Lins like this ArrayList<String> list = new List<>(); and then replace contents[i] = s.nextLine().replace(" ", ",");with list.add(s.nextLine().replace(" ", ","));. After this you will not need counter "i" anymore and break you loop in if condition. Just add scanner.hasNext() in a while condition.
Your looping condition should be based on Scanner.hasNextLine and you don't need the variable i. Use an ArrayList to score an unknown amount of elements.
Scanner s = new Scanner(new FileReader(args[0]));
final List<String> contents = new ArrayList<>();
while(s.hasNextLine()){
contents.add(s.nextLine().replace(" ", ","));
}
This can be shortened using Files.lines. Note that this throws an IOException that you will need to handle.
final List<String> contents = Files.lines(Paths.get(args[0]))
.map(s->s.replace(" ", ",")).collect(Collectors.toList());

Why is FileNotFoundException popping up? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I am trying to print Ben, Adam, John and Smith into a txt file with the names on separate lines. I am partly successful, however I keep getting FileNotFoundException at the end after the code runs. Why is that?
"Ben Adam John Smith" passes through String names
File Writing code:
public String writeYourName(String names) throws Exception {
PrintWriter output = new PrintWriter(new BufferedWriter(new FileWriter("names.txt")));
for(int i = 0; i < 1; i++) {
output.write(names);
}
output.close();
Scanner scan1 = new Scanner(new File("names.txt"));
while(scan1.hasNext()) {
if(scan1.hasNext()) {
System.out.println(scan1.next());
}
}
return names;
}
Test file for FileWriting:
FileWriting fileWriting = new FileWriting();
FileReading fileReading = new FileReading();
fileWriting.writeYourName("Ben Adam John Smith");
System.out.println(fileReading.readName1(fileWriting.writeYourName("Fred")));
Code that the error points to:
public class FileReading {
public String readName1(String nameFile) throws Exception {
-> Scanner scan = new Scanner(new File(nameFile)); <-
String name = scan.next();
String nextLine = "";
while(scan.hasNextLine()) {
nextLine = scan.nextLine();
}
return name + " " + nextLine;
}
Test file for FileReading:
System.out.println(fileInput.readName1("namefile.txt"));
You are trying to read a file where the filename consists of a name or names here:
fileReading.readName1(fileWriting.writeYourName("Fred"))
as writeYourName doesn't return a file name but a string of names of persons (or in this case, one name, of one person: Fred):
return names;

How to print words that only have more than 10 characters from file? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I've got this question and I'm not very sure how to answer it - I am able to read the file but unsure on how to display only the words with more than 10 characters
Although other answers are correct , I recommend using scanner class to read files, as it safely allows to detect end of file conditions and has simpler/more useful utility methods:-
Scanner input = new Scanner(new File("file.txt"));
while(input.hasNextLine())
{
String word = input.nextLine();
if(word.length()>10){
System.out.println(word)
}
}
This should work:
private static void readFile(File fin) throws IOException {
FileInputStream fis = new FileInputStream(fin);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
String line = null;
while ((line = br.readLine()) != null) {
if(line.length()>10) System.out.println(line);
}
br.close();
}
Suposing you have the word in a String variable called word:
if (word.length() > 10)
System.out.println(word);
PS: google before asking!!
Here's some pseudo code to help you get started
create empty list //where we'll add all the >10char words
read file(split per newline) //see the apache commons api
for each line
split on space
for each word in splitted sentence
if wordLength > 10 add to empty list
print each entry in your filled list
Here is your logic.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
public class Test {
public static void main(String[] args) throws Exception{
FileInputStream fis = new FileInputStream(new File("your.txt")); // path for the text file
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
String line = null;
while ((line = br.readLine()) != null) {
String st[] = line.split(" ");
for(int i=0; i<st.length; i++){
if(st[i].length()>10) System.out.println(st[i]);
}
}
}
}

String split based on column (Java) [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
New to java. I want to read in a file that has lines formatted like this
en Fox 3 1344
en Bird 19 144
en Dog 93 1234
For each line I want to pick the contents of column 2 and 3. In the case of the first line "Fox" and "3". and display them. So far this is what I have.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class pagecounts {
public static void main(String[] args) throws FileNotFoundException {
String content = new Scanner(new File("filename")).useDelimiter("\\Z").next();
*// letter in column 2 and 3 pick code goes here.*
System.out.println(content);
}
}
Any help will be appreciated.
Assuming that each column can contain only one value (word/number) you can use Scanner to read all tokens form one line and use only these which interest you.
try(Scanner sc = new Scanner(new File(path))){//try-with-resources
//will automatically close stream to file
while (sc.hasNext()){
String col1 = sc.next();
String col2 = sc.next();
int col3 = sc.nextInt();//you can also use next() if you want to get this token as String
int col4 = sc.nextInt();//same here
System.out.printf("%-15s %d%n", col2, col3);
}
}
You can also read file line by line and split each line on space
try(Scanner sc = new Scanner(new File(path))){//try-with-resources
//will automatically close stream to file
while (sc.hasNextLine()){
String line = sc.nextLine();
String[] tokens = line.split("\\s+");//I assume there are no empty collumns
System.out.printf("%-15s %s%n",tokens[1],tokens[2]);
}
}
You can also treat this file as CSV file (Comma Separated Values) where values are separated with space. To parse such file you can use library like OpenCSV with separator defined as space
try(CSVReader reader = new CSVReader(new FileReader(path),' ')){
String[] tokens = null; // ^--- use space ' ' as delimiter
while((tokens = reader.readNext())!=null)
System.out.printf("%-15s %s%n",tokens[1],tokens[2]);
} catch (IOException e) {
e.printStackTrace();
}
Use split:
System.out.println(content.split(" ")[1] + " " + content.split(" ")[2]);

Read data from file into an array Java [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
In my program, I am asking users for input for a subject name and a subject code which i pass through to a subjects.txt file eg:
Inside the TestSubject class -
//ask the user to input a subject name
System.out.println("Please enter a Subject Name");
//assign each input to a side
String subjectName = input.nextLine();
//ask the user to input a subject code
System.out.println("Please enter a Subject Code");
String subjectCode = input.nextLine();
//add records to the file
subject.addRecords(subjectName, subjectCode);
Inside the subject class -
//add the records of valid subject name and subject code
public void addRecords(String name, String code) {
try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("subjects.txt", true)))) {
out.printf(name);
out.printf("\n");
out.printf(code);
out.printf("\n");
out.close();
}catch (IOException e) {
}
}
I then want to read this file and pass the data through to an arraylist. The file might look something like:
Testing 1
ABC123
Testing 2
DEF456
Testing3
GHI789
I want to pass it through to an arraylist so then I can then process other methods against this array such as sorting, see if any are the same etc.
//read data from subjects file and place in an array
public void readData(){
Scanner input = new Scanner("subjects.txt");
while (input.hasNext()) {
String subjectName = input.nextLine();
String subjectCode = input.nextLine();
}
ArrayList<String> subjectNames = new ArrayList<String>();
ArrayList<String> subjectCodes = new ArrayList<String>();
//add the input to the arrays
subjectNames.add(subjectName);
subjectNames.add(subjectCode);
//display the contents of the array
System.out.println(subjectNames.toString());
System.out.println(subjectCodes.toString());
}
Even if there is a good tutorial around that I might be able to be pointed in the right direction...
Thanks for editing your post. Much easier to help when I can see what's causing problems.
You're checking hasNext() once every two lines. Should be checked every line because you shouldn't trust the text file to be what you expect and should display an informative error message when it isn't.
You're also declaring the strings inside the scope of the loop so nothing outside the loop even knows what they are. Shoving subjectCode into into the subjectNames collection is probably not what you want. As it is, each nextline() is stepping on the last string value. That means you're forgetting all the work done in previous iterations of the loop.
The collections.add() calls, not the strings, should be in the loop. Make sure to declare the collections before the loop and put their add calls in the loop. See if you get useful results.
Give "Reading a plain text file in Java" a read.
Regarding your tutorial query, I often find some good basic examples on this site including one for reading from a file as referenced in the link. Using the main principles of that example here is one way you could try and read the lines from your file:
public static void main(String[] args){
ArrayList<String> subjectNames = new ArrayList<String>();
ArrayList<String> subjectCodes = new ArrayList<String>();
//Path leading to the text file
Path data = Paths.get(System.getProperty("user.home"), "Desktop", "file.txt");
int count = 0;//Will indicate which list to add the current line to
//Create a buffered reader to read in the lines of the file
try(BufferedReader reader = new BufferedReader(new FileReader(data.toFile()))){
String line = "";
while((line = reader.readLine()) != null){//This statement reads each line until null indicating end of file
count++;//Increment number changing from odd to even or vice versa
if(count % 2 == 0){//If number is even then add to subject codes
subjectCodes.add(line);
} else {//Otherwise add to subject names
subjectNames.add(line);
}
}
} catch (IOException io){
System.out.println("IO Error: " + io.getMessage());
}
System.out.println("Codes: ");
display(subjectCodes);
System.out.println("\nNames: ");
display(subjectNames);
}
private static void display(Collection<String> c){
for(String s :c){
System.out.println(s);
}
Hope it helps!

Categories