Scanning in file - java

I'm trying to scan the following sentences into my Java program as strings:
The cat in the hat
The cat sat on the mat
Pigs in a blanket
and then read it into a list using whileloop and hasNextLine()method.
My problem is that I am unsure how to read this in as it is not a designated text file and I must utilizeargs [0]
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.ArrayList;
public class Scan {
public static void main(String[] args) throws FileNotFoundException{
//Opens a scanner into the file
File file = new File( args [0] );
try (Scanner scan = new Scanner(file))
{
ArrayList<String> list = new ArrayList<String>();
while(scan.hasNextLine())
{
list.add(scan.nextLine());
}
}
}
}

If you're just trying to output the list, use a for each style loop is the fastest way to check if you're doing it right.
for (String val : list)
{
System.out.println(val);
}

I think you should replace your existing code with the one below:
ArrayList<String> list = new ArrayList<String>();
Scanner scan = new Scanner(System.in);
while (scan.hasNextLine()) {
list.add(scan.nextLine());
}
scan.close();
Use System.in instead of new File(args[0]). System.in reads from the standard input (i.e. whatever is entered in with the keyboard). This should work both on an IDE and with command line input.
I hope this helps.

Related

Reading a file in Java with Scanner

I'm trying to get a program to read a text file but it's throwing a FileNotFoundException even though I have the potato.txt file set in the project directory.
import java.io.File;
import java.util.Scanner;
public static void main(String[] args) {
String potato = "potato.txt"; // assume this line can't be changed at all
Scanner scan = new Scanner(new File(potato)); // throws FileNotFoundException
while (scan.hasNextLine()) {
String line = scan.nextLine();
System.out.println(line);
}
}
}
Try using the full Path, like this:
File file = new File("C:/temp/potato.txt"); //This is just an example path, look up your files path and put it here.
Scanner scan = new Scanner(file);
Also, don't forget to close your scanner when done (after your while-loop):
scan.close();

How to read particular value from a segement in EDI file?

For example, below is the data from my EDI file:
ISA*00* *00* *ZZ*FOUNDTHISORG *ZZ*PLUS05931283*160411*1551*^*00501*111512123*0*P*:~
GS*BE*FOUNDTHISORG*PLUS*20160411*1551*111512123*X*005010X220A1~
ST*834*111512124*005010X220A1~
BGN*00*111512123*20160411*1551*PT***4~
REF*38*5931283~
DTP*382*D8*20160411~
N1*P5*FOUNDTHISORG*FI*13-5581829~
N1*IN*Plus*FI*13-5581829~
INS*Y*18*030*XN*A***RT~
REF*0F*094282627~
REF*1L*593128300010002~
DTP*336*D8*19670605~
DTP*286*D8*19900331~
NM1*IL*1*Fname*Lname*H***34*094282627~
PER*IP**HP*6317444093~
N3*587 Some Drive~
N4*Ridge*NY*11961~
DMG*D8*19350319*F*R~
HD*030**DEN**IND~
DTP*348*D8*20160101~
INS*Y*18*030*XN*A***RT~
REF*0F*089307096~
REF*1L*593128300010002~
DTP*336*D8*19630917~
DTP*286*D8*19950201~
NM1*IL*1*Sname*Rname*A***34*089307096~
PER*IP**HP*7184283161~
N3*249-36 51st Avenue~
N4*long Neck*NY*11362~
DMG*D8*19390114*F*I~
HD*030**DEN**IND~
DTP*348*D8*20160101~
INS*Y*18*030*XN*A***RT~
Now I need values of REF 0F segment. Can you please write or suggest me a java code to read all the values in that segment. THere are about 600 segments like these and I need to read all of them and store them in a List or an Array.
I tried and wrote the code for my requirement. below is the code:
package com.FileOperations;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.LinkedList;
import java.util.Scanner;
public class EDIRead {
public static void main(String[] args) throws FileNotFoundException {
LinkedList<String> list = new LinkedList<String>();
String path = "D:/FIleIO/fordfnd_elig.26448.txt";
Scanner scanner = new Scanner(new File(path));
while (scanner.hasNext()) {
String line = scanner.nextLine();
if(line.equals("eof"))
break;
if (line.startsWith("REF*0F")) {
line = line.substring(line.indexOf("0F*")+3);
line = line.replaceAll("~", "");
list.add(line);
}
}
scanner.close();
System.err.println("Completed Parsing, here is the list of entries : ");
for(String line : list){
System.out.println(line);
}
}
}
My sincere apologies if you felt that my question wasn't clear. Thanks everyone.

How do I read a text file into an arraylist, excluding lines that contain certain words?

I am trying to make a program that reads a text file named text.txt into an ArrayList. And then after that it must remove any lines of the text that contain the words "I love cake"
So say this is the text from the file:
I love cake so much
yes i do
I love cake
I dont care
Here is my code. I have it reading the file but I don't understand how I can remove certain lines (the ones that contain "I love cake").
import java.io.*;
import java.util.*;
public class Cake {
public static void main(String[] args) throws Exception {
File fileIn = new File("text.txt");
ArrayList<String> text = new ArrayList<String>();
Scanner s= new Scanner(fileIn);
String line;
while (s.hasNextLine()) {
line = s.nextLine();
System.out.println(line);
}
s.close();
}
}
Java8:
Path file = new File("text.txt").toPath();
List<String> linesWithoutCake = Files.lines(file)
.filter(s -> !s.contains("I love cake"))
.collect(Collectors.toList());
You can continue using the stream with lines that don't contain your pattern. For example count them:
long count = Files.lines(file).filter(s -> !s.contains("I love cake")).count();
Try the String.contains() method.
Your code would look like this:
import java.io.*;
import java.util.*;
public class Cake {
public static void main(String[] args) throws Exception {
File fileIn = new File("text.txt");
ArrayList<String> text = new ArrayList<String>();
Scanner s = new Scanner(fileIn);
String line;
while (s.hasNextLine()) {
line = s.nextLine();
if(!line.contains("I love cake")){ //If "I love cake" is not in the line
System.out.println(line); //Then it's ok to print that line
text.add(line); //And we can add it to the arraylist
}
}
s.close();
}
}

Change a program to accept command line arguments

I have the following code and would like to modify it to accept command line arguments instead of reading a file using scanner. Can you point me to some change I need to make in the code in order to do so ? Any help is appreciated. I will have a file called prgm.cmd and will execute it on UNIX as follows. prgm.cmd is the actual argument !
java Commander prgm.cmd
right now I am only able to have the program work by using
java Commander < prgm.cmd
CODE
import java.util.Scanner;
import java.util.Map;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class Commander
{
public static void main(String[] args)
{
Map<String,Integer> expression = new HashMap<String,Integer>();
ArrayList<String> list = new ArrayList<String>();
Scanner sc = new Scanner(System.in);
while(true)
{
list.add(sc.nextLine());
if(!sc.hasNextLine()) break;
}
ArrayList<String> tokens = new ArrayList<String>();
ArrayList<String> PRINT = new ArrayList<String>();
for(String element : list) {
StringTokenizer st = new StringTokenizer(element);
if(!element.startsWith("PRINT")) {
while(st.hasMoreTokens()) {
tokens.add(st.nextToken());
}
expression.put(tokens.get(0),Integer.parseInt(tokens.get(2)));
tokens.clear();
} else {
while(st.hasMoreTokens())
PRINT.add(st.nextToken());
System.out.println(expression.get(PRINT.get(1)));
PRINT.clear();
}
}
}
}
SAMPLE COMMAND FILE: PRGM.CMD
A = 6
C = 14
PRINT C
B = 12
C = 8
PRINT A
OUTPUT
14
6
public static void main(String[] args)
// ^^^^^^^^^^^^^
When you run your program with something like:
java progname arg1 arg2
the arguments appear in the string array handed to main(). You just extract them from there and do what you need.
The following small (but complete) program shows this in action. It will echo back your arguments, one per line:
public class Test {
public static void main(String[] args) {
for (int i = 0; i < args.length; i++)
System.out.println (args[i]);
}
}
That's to get the commands as arguments to the program.
If, instead, you want to still have the commands in a file and just supply the file name to the program, you simply need to change your scanner to use a file based reader rather than System.in. The following program accepts a file name argument then echos it to the screen:
import java.io.FileInputStream;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
try {
Scanner sc = new Scanner (new FileInputStream(args[0]));
while (sc.hasNextLine())
System.out.println (sc.nextLine());
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
}
You can even make it selectable, like UNIX filter programs using - to indicate standard input.
If you want to use a file if provided but revert to standard input if not, you can do something like:
Scanner sc;
if (args.length > 0)
sc = new Scanner (new FileInputStream(args[0]));
else
sc = new Scanner (System.in);
// Now just use scanner as before

Scanner is not working on StringBuilder

I wrote a program that must take input from a file and extract only text from it while saving its contents into an array. My text file contents are:
There is some!text.written%in
the FILE[That]=Have+to`be==separated????
And what I have tried to code is:
public static void main(String[] args) throws FileNotFoundException, IOException {
BufferedReader file = new BufferedReader(new FileReader("mfile.txt"));
List<String> list = new ArrayList();
String str;
StringBuilder filedata = new StringBuilder();
Scanner toknizer = new Scanner(filedata.toString());
while((str=file.readLine())!=null){
filedata.append(str);
}
toknizer.useDelimiter("[^a-z]");
while(toknizer.hasNext()){
list.add(toknizer.next());
}
System.out.println(list);
}
at this time I only want to extract text that is written in small alphabets. But the program is printing out an empty list. Debugging revealed that toknizer.hasNext() is returning false in while(toknizer.hasNext()).
What is wrong? Am I using wrong regular expression? I got the idea of using [^a-z] from here.
Scanner toknizer = new Scanner(filedata.toString());
You just created a Scanner around an empty string.
That's not going to have any tokens.
Strings are immutable; appending to the StringBuilder later does not affect the existing String instance you passed to the Scanner.
Why not just do it like this?
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public static void main(String[] args) {
List<String> list = new ArrayList<String>(); // If List is generic then ArrayList should be too
Scanner input = null;
try {
input = new Scanner(new File("mfile.txt"));
} catch(Exception e) {
System.out.println(e.getStackTrace());
}
input.useDelimiter("[^a-z]");
while(input.hasNext()) {
String parse = input.next();
if(!parse.equals("")) {
list.add(parse);
}
}
System.out.println(list.toString());
}
Now you don't have to use a BufferedReader, FileReader or a StringBuilder.

Categories

Resources