Scanning a text file with Java - java

The purpose is to print-out a list of names from a .txt file. The code I've used is below.
import java.util.ArrayList;
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class FileScanner3 {
public static void main(String args []) throws FileNotFoundException {
ArrayList<String> names = new ArrayList<String>();
String inName;
//Setup a scanner to read from a text file
Scanner in = new Scanner(new File("namefile.txt").getAbsoluteFile());
while (in.hasNextLine()) {
inName = in.next();
//Use next() to read string
names.add(inName);
}
//Tidy up by closing files
in.close();
//Print names ArrayList
for(int i =0; i<names.size(); i++) {
System.out.println((i + 1) + "\t" + names.get(i));
}
}
}
The error that I get is this:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at FileScanner3.main(FileScanner3.java:17)
If anyone is able to tell me what is wrong, that would be fantastic!
Edit: Spelling

Without the text file, it is hard to guess, but I suppose there is a blank line at the end of the file. You could prevent this error by chaning the inner loop to
while (in.hasNext()) {
inName = in.next();
//Use next() to read string
names.add(inName);
}
I hope it helps.

Related

Need to get a line from a file onto queue and not the whole file text

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.

How to read two or more word separeted by comma in a line in a CSV file in Java?

Here is my CSV file:
11608030,12345
11608045,54321
Here is my code:
package csvtest;
import java.util.ArrayList;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Test {
private ArrayList<Long> account_number = new ArrayList<Long>();
private ArrayList<String> password = new ArrayList<String>();
public Test() throws FileNotFoundException {
Scanner scanner = new Scanner(new File("E:\\account.csv"));
scanner.useDelimiter(",");
while(scanner.hasNext()){
this.account_number.add(Long.parseLong(scanner.next()));
this.password.add(scanner.next());
}
System.out.println(account_number);
}
}
and in the main class there is only one command
Test test = new Test();
but when i run this code i got a message like this
Exception in thread "main" java.util.NoSuchElementException at java.util.Scanner.throwFor(Scanner.java:862) at
java.util.Scanner.next(Scanner.java:1371) at
csvtest.Test.(Test.java:28) at
csvtest.CSVTest.main(CSVTest.java:21)
C:\Users\hp\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53:
Java returned: 1 BUILD FAILED (total time: 0 seconds)
whats wrong with my code??
need help!!!
thanks in advance :)
You should use scanner.useDelimiter(",|\\n"); The issue that you originally had was that the second scanner.next() read in "12345\n11608045" since you didn't specify that a newline could be a delimiter as well. So when scanner.next() was called the last time there wasn't anything to read from since that second call to next() read two of your values.
scanner.next() gets you a line from the file, you then need to split that line into your comma seperated values:
See example:
#Test
void parseAccountsCsvFile() throws FileNotFoundException {
ArrayList<Long> account_number = new ArrayList<Long>();
ArrayList<String> password = new ArrayList<String>();
Scanner scanner = new Scanner(new File("accountsCsvTest.txt"));
while(scanner.hasNext()){
String scannerLine = scanner.next();
String[] values = scannerLine.split(",");
account_number.add(Long.valueOf(values[0]));
password.add(values[1]);
}
System.out.println(account_number);
System.out.println(password);
scanner.close();
}
}
Output:
[11608030, 11608045]
[12345, 54321]
I think that is what you are looking for.

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.

Reading file in java on Mac

I am doing a tutorial on java and the video I am at now deals with FileReading, but it is for windows and I am on a mac. Please help
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class App {
public static void main(String[] args) throws FileNotFoundException {
String fileName = "/Users/--MyUsername--/Desktop/test.rtf";
File textFile = new File(fileName);
Scanner in = new Scanner(textFile);
int value = in.nextInt();
System.out.println("Read value: " + value);
in.nextLine();
int count = 2;
while(in.hasNextLine()){
String line = in.nextLine();
System.out.println(count + ": " + line);
count++;
}
in.close();
}
}
and this is the error that I am getting
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:840)
at java.util.Scanner.next(Scanner.java:1461)
at java.util.Scanner.nextInt(Scanner.java:2091)
at java.util.Scanner.nextInt(Scanner.java:2050)
at L37ReadingTextFiles.App.main(App.java:17)
Please help
You are trying to read integers from the file, but the content is not integer, please use String value = in.next(); instead of int value = in.nextInt();
The problem is probably with the .rtf file. There might be a way to get that type of file to work as expected in java, but for a beginner, I would recommend making it a .txt file.

read input from txt file names(one word) and (ints). write to output file the lists with ages then names

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);
}
}

Categories

Resources