Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

java question ,show code and explain! I have a file call input.txt contain: Bost

ID: 3804368 • Letter: J

Question

java question ,show code and explain!

I have a file call input.txt contain:

Boston (MA), New York City (NY, CT, NJ)
New York City (NY, CT, NJ), Philadelphia (PA, NJ)
Philadelphia (PA, NJ), Baltimore (MD)
Baltimore (MD), Washington (DC)
Washington (DC), Charlotte (NC)

My code:

public static void main(String[] args) {

   File file = new File("input.txt");
   String[] array;
       try {
           Scanner in = new Scanner(file);
           Graph graph = new Graph();
   while (in.hasNextLine()) {
       String key = in.nextLine();
       array = key.split("please help here"); // add something for me.
       System.out.println(array[0] + " " + array[1]);
  
}

   }catch(FileNotFoundException e){
           e.printStackTrace();
       }
}

The output I want is

Boston (MA) New York City (NY, CT, NJ)

New York City (NY, CT, NJ) Philadelphia (PA, NJ)

Philadelphia (PA, NJ) Baltimore (MD)

Baltimore (MD) Washington (DC)
Washington (DC) Charlotte (NC)

Explanation / Answer

Let me give an overview about reading the files from the txt file and printing the content into the console. It can be done in many ways, but the efficient way to read a file is to use the BufferedReader which elaborates them in reading the large text files content by ranging from MB's to GB's in size.

The program which you have provided is not finding the desired path of a input.txt file, As per Java Community standards, The path should be used is Absolute i.e, for example:- F:\javaFiles\input.txt.

Code:-

import java.io.*;
class ReadContentFromFile {
public static void main(String args[]) {

try {

FileInputStream fis = new FileInputStream("F:\javaFiles\input.txt");
DataInputStream dis = new DataInputStream(fis);
BufferedReader br = new BufferedReader(new InputStreamReader(dis));
String str;
while ((str = br.readLine()) != null) {
System.out.println(str);
}
dis.close();
} catch (Exception exp) {

System.err.println("Error: " + exp.getMessage());

}
}
}