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.
Related
I'm having trouble properly getting one line of text at a time from a file onto a queue without taking the whole file into the queue. For example, I'd like only Write a program that reads a Java source file as an argument and produces an index of all identifiers in the file. For each identifier, print all lines in which it occurs. For simplicity, we will consider each string consisting only of letters, numbers, and underscores an identifier.
Declare a Scanner in for reading from the source file and call in.useDelimiter("[^A-Za-z0-9_]+") Then each call to next returns an identifier.
public class Main { to get added to the queue but instead the whole file text is put into the queue instead of a line at a time. Sorry if my question is unclear
// Write a program that reads a Java source file as an argument and produces an index of all
// identifiers in the file. For each identifier, print all lines in which it occurs. For simplicity,
// we will consider each string consisting only of letters, numbers, and underscores an identifier.
// Declare a Scanner in for reading from the source file and call in.useDelimiter("[^A-Za-z0-9_]+").
// Then each call to next returns an identifier.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class E_15 {
public static void main(String[] args) throws FileNotFoundException
{
// get scanner input from file
Scanner fileInput = new Scanner(new File ("C:/Users/ramir/IdeaProjects/PA_7/src/Main.java"));
Queue<String> test = new LinkedList<String>();
ArrayList<String> phrase = new ArrayList<String>();
/*
List<String> result = new ArrayList<String>();
Scanner s = new Scanner(is);
s.useDelimiter(delimiter);
*/
// Iterates till end of file
while (fileInput.hasNextLine())
{
// Here is the issue. Data will end up
// containing the whole file instead of only that line
String data = fileInput.nextLine();
Scanner in = new Scanner(data);
in.useDelimiter("[^A-Za-z0-9_]+");
// I believe around here or before is the issue that I'm having.
// It adds all the file instead of only that line
// Also trying to figure out how to display each line that it's displayed on
// What the first one should look like for example
// 0: public occurs in:
// public class Main {
// public static void main(String[] args) {
//System.out.println(data);
test.add(data);
while(in.hasNext())
{
// Getting each phrase/word into ArrayList
String token = in.next();
phrase.add(token);
}
in.close();
}
int index = 0;
// This part works fine
for(String num : phrase)
{
// printing the key
System.out.println(index + ": " + num + " occurs in:");
// printing the values
// This to print out what
for(String line : test)
{
System.out.println(line);
}
System.out.println();
++index;
}
}
}
// Just java class get file front
// This is fine
public class Main {
public static void main(String[] args) {
int a_1 = 100;
System.out.println(a_1);``
}
}
I'd like it to only show System.out.println(a_1) because the line that's it's on See This
. I'm also have trouble printing it in all the lines that occur.
import java.io.*;
import java.util.Scanner;
public class ReadLineByLineExample2
{
public static void main(String args[])
{
try
{
//the file to be opened for reading
FileInputStream fis=new FileInputStream("Demo.txt");
Scanner sc=new Scanner(fis); //file to be scanned
//returns true if there is another line to read
while(sc.hasNextLine())
{
System.out.println(sc.nextLine()); //returns the line that was skipped
}
sc.close(); //closes the scanner
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
Try studying the above code. I hope it will help. Otherwise, you might need to open this link for more detail.
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();
}
}
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.
When finished output should be:
15 Michael
16 Jessica
20 Christopher
19 Ashley
etc.
I am not that good at this and would like any input whatsoever on how to get the int and strings to print line by line. I have avoided an array approach because I always have difficulty with arrays. Can anyone tell me if I am on the right track and how to properly parse or type cast the ints so they can be printed on a line to the output file? I have been working for days on this and any help would be much appreciated! Here is what I have so far.
import java.io.PrintWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class NameAgeReverse
{
public static void main (String[] args)
{
System.out.println("Programmed by J");
String InputFileName;
String OutputFileName;
Scanner keyboard = new Scanner(System.in);
System.out.print("Input file: ");
InputFileName = keyboard.nextLine();
System.out.print("Output file: ");
OutputFileName = keyboard.nextLine();
Scanner inputStream = null;
PrintWriter outputStream = null;
try
{
inputStream = new Scanner(new FileInputStream("nameAge.txt"));
outputStream =new PrintWriter(new FileOutputStream("ageName.txt"));
}
catch(FileNotFoundException e)
{
System.out.println("File nameAge.txt was not found");
System.out.println("or could not be opened.");
System.exit(0);
}
int x = 0;
String text = null;
String line = null;
while(inputStream.hasNextLine())
{
text = inputStream.nextLine();
x = Integer.parseInt(text);
outputStream.println(x + "\t" + text);
}
inputStream.close();
outputStream.close();
}
}
Here are my error messages:
Exception in thread "main" java.lang.NumberFormatException: For input string: "Michael"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:492)
at java.lang.Integer.parseInt(Integer.java:527)
at NameAgeReverse.main(NameAgeReverse.java:52)
text = inputStream.nextLine(); will read the whole line of text with both name and age. Assuming the format of every line in your input file is age name, you can do the following parse every line of text into desirable values. Note that this won't work out of the box with the rest of your code. Just a pointer:
text = inputStream.nextLine().split(" "); // split each line on space
age = Integer.parseInt(text[0]); // age is the first string
name = text[1];
This should work:
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
public class ReadWriteTextFile {
final static Charset ENCODING = StandardCharsets.UTF_8;
public static void main(String... aArgs) throws IOException{
List<String> inlines = Files.readAllLines(Paths.get("/tmp/nameAge.txt"), ENCODING);
List<String> outlines = new ArrayList<String>();
for(String line : inlines){
String[] result = line.split("[ ]+");
outlines.add(result[1]+" "+result[0]);
}
Files.write(Paths.get("/tmp/ageName.txt"), outlines, ENCODING);
}
}
I'm trying to remove the commas from the following txt file:
abcd,efgh,ijkl
mnop,qrst,uvwx
yzzz,0123,4567
8910
My code goes something like this:
public static ArrayList readFileByLine(ArrayList list, String fileName){
try{
File file = new File(fileName);
Scanner reader = new Scanner(file);
reader.useDelimiter(",");
while(reader.hasNext()){
String s = reader.next();
s= s.trim();
s= s.replaceAll("," , "");
list.add(s);
}
reader.close();
}
catch(FileNotFoundException e){ System.err.println("Error: " + e.getMessage());}
return list;
}
I'm trying not to use a regex unless absolutely necessary, if you recommend that I use a regex please explain what it does! Thanks for the help!
Your code runs fine. I think you were running into other issues, I'm not sure what. Here's the code that I used (your code with some modifications):
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args){
List<String> list = readFileByLine(new ArrayList<String>(), "/Users/hassan/Library/Containers/com.apple.TextEdit/Data/Desktop/file.text");
for(String s : list){
System.out.println(s);
}
}
public static List<String> readFileByLine(ArrayList<String> list, String fileName){
try{
File file = new File(fileName);
Scanner reader = new Scanner(file);
reader.useDelimiter(",");
while(reader.hasNext()){
String s = reader.next();
s= s.trim();
s= s.replaceAll("," , "");
list.add(s);
}
reader.close();
}
catch(FileNotFoundException e){ System.err.println("Error: " + e.getMessage());}
return list;
}
}
This code works (try it!). I should mention that the way I'm using this code, passing an ArrayList as the first argument is useless, since you can just make a new ArrayList at the beginning of the readFileByLine function. I'm not sure if you did it this way because you want to re-add strings to the array later on, so I left it alone.