How to ignore first line of .txt when using Scanner class - java

I have a text file that reads:
Description|SKU|Retail Price|Discount
Tassimo T46 Home Brewing System|43-0439-6|17999|0.30
Moto Precise Fit Rear Wiper Blade|0210919|799|0.0
I've got it so that I read everything, and it works perfectly, save for the fact that it reads the first line, which is a sort of legend for the .txt file, which must be ignored.
public static List<Item> read(File file) throws ApplicationException {
Scanner scanner = null;
try {
scanner = new Scanner(file);
} catch (FileNotFoundException e) {
throw new ApplicationException(e);
}
List<Item> items = new ArrayList<Item>();
try {
while (scanner.hasNext()) {
String row = scanner.nextLine();
String[] elements = row.split("\\|");
if (elements.length != 4) {
throw new ApplicationException(String.format(
"Expected 4 elements but got %d", elements.length));
}
try {
items.add(new Item(elements[0], elements[1], Integer
.valueOf(elements[2]), Float.valueOf(elements[3])));
} catch (NumberFormatException e) {
throw new ApplicationException(e);
}
}
} finally {
if (scanner != null) {
scanner.close();
}
}
return items;
}
How do I ignore the first line using the Scanner class?

Simply calling scanner.nextLine() once before any processing should do the trick.

how about calling scanner.nextLine() as outside your loop.
scanner.nextLine();//this would read the first line from the text file
while (scanner.hasNext()) {
String row = scanner.nextLine();

scanner.nextLine();
while (scanner.hasNext()) {
String row = scanner.nextLine();
....

Related

How to add comma seperated string and int into two different arraylists [java]

Say I have strings and integers being read from a file and seperated by a comma and I want to add them into two different arrayLists.
hamburger,15
cheese,10
soda,15
How would I go about doing this? I intially used nextLine() to add them into one arraylist and extract the integer and erase the comma but this wasn't working for arrayLists. I also tried using nextInt() to just grab the int's but was given an exception.
public static void readFile(ArrayList items, ArrayList cost)
{
String intValue = "";
try
{
Scanner read = new Scanner(new File("Menu.txt"));
while (read.hasNext())
{
items.add(read.nextLine());
}
read.close();
for (int i = 0; i < items.size(); i++)
{
intValue = items.indexOf(i).replaceAll("[^0-9]", "");
int value = Integer.parseInt(intValue);
cost.add(value);
}
System.out.println(item);
System.out.println(cost);
}
catch(FileNotFoundException fnf)
{
System.out.println("File was not found.");
}
}
my end result would be:
items = [hamburger, cheese, soda]
cost = [15, 10, 15]
public static void readFile(List<String> items, List<Integer> costs) {
try {
Scanner read = new Scanner(new File("Menu.txt"));
while (read.hasNext()) {
String line = read.nextLine();
String[] itemsAndCosts = line.split(",");
items.add(itemsAndCosts[0]);
costs.add(Integer.parseInt(itemsAndCosts[1]));
}
read.close();
System.out.println(items);
System.out.println(costs);
} catch (FileNotFoundException fnf) {
System.out.println("File was not found.");
}
}
Use List<String> instead of ArrayList.
You can split the line on the , and then you have an array of 2 elements, item and cost. (Note: will only work if there is only one , per line). You can also use .subString(...), but for me, splitting is cleaner.
Use try-with-resources so you don't need to do .close():
try (Scanner read = new Scanner(new File("Menu.txt"))) {
while (read.hasNext()) {
String line = read.nextLine();
String[] itemsAndCosts = line.split(",");
items.add(itemsAndCosts[0]);
costs.add(Integer.parseInt(itemsAndCosts[1]));
}
System.out.println(items);
System.out.println(costs);
} catch (FileNotFoundException fnf) {
System.out.println("File was not found.");
}

Where do I place the return of a function in JAVA?

I'm trying to figure out how to make a function in JAVA that searches through a document line per line:
First I initialize the file and a reader, then convert each line to a string in an ArrayList; after that I try to check the ArrayList against a String to then return the position of the ArrayList as a string.
So for example I have a text containing:
1 - Somewhere over the rainbow
2 - Way up high.
Converted to ArrayList, if then searched for: "Somewhere"; then it should return the sentence "Somewhere over the rainbow";
Here is the code I tried; but it keeps returning 'null';
String FReadUtilString(String line) {
File file = new File(filepath);
ArrayList<String> lineReader = new ArrayList<String>();
System.out.println();
try {
Scanner sc = new Scanner(file);
String outputReader;
while (sc.hasNextLine()) {
lineReader.add(sc.nextLine());
}
sc.close();
for(int count = 0; count < lineReader.size(); count++) {
if(lineReader.get(count).contains(line)){outputReader = lineReader.get(count);}
}
} catch (Exception linereadeline) {
System.out.println(linereadeline);
}
return outputReader;
}
I refactor your code a bit, but I keep your logic, it should work for you:
String FReadUtilString(String line, String fileName){
File file = new File(fileName);
List<String> lineReader = new ArrayList<>();
String outputReader = "";
try (Scanner sc = new Scanner(file))
{
while (sc.hasNextLine()) {
lineReader.add(sc.nextLine());
}
for (int count = 0; count < lineReader.size(); count++){
if (lineReader.get(count).contains(line)){
outputReader = lineReader.get(count);
}
}
}
catch (Exception linereadeline) {
System.out.println(linereadeline);
}
return outputReader;
}
NOTE: I used the try-with-resource statement to ensure the closing of the Scanner.
A more succinct version:
String fReadUtilString(String line, String fileName) {
try (Stream<String> lines = Files.lines(Paths.get(fileName))) {
return lines.filter(l -> l.contains(line)).findFirst();
}
catch (Exception linereadeline) {
System.out.println(linereadeline); // or just let the exception propagate
}
}

Reading integers from text file

I am trying to read integers from a text file but I failed.
(It fails to read even the first integer)
public void readFromFile(String filename) {
File file = new File(filename);
try {
Scanner scanner = new Scanner(file);
if (scanner.hasNextInt()) {
int x = scanner.nextInt();
}
scanner.close();
} catch (FileNotFoundException e) {
System.out.println("File to load game was not found");
}
}
The error I get is: NoSuchElementException.
The file looks like this:
N,X1,Y1,X2,Y2,X3,Y3
While n equals 3 in this example.
I call this method a in the main method like this:
readFromFile("file.txt");
I am not sure whether you would like to display only the integers after separating them from the string. If that is the case, I would suggest you to use BufferedInputStream.
try(BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)))){
String input = br.readLine();
int count = 0;
for(int i = 0; i < input.length()- 1; i++){
if(isNumeric(input.charAt(i))){
// replace the Sysout with your own logic
System.out.println(input.charAt(i));
}
}
} catch (IOException ex){
ex.printStackTrace();
}
where isNumeric can be defined as follows:
private static boolean isNumeric(char val) {
return (val >= 48 && val <=57);
}
Scanneruses whitespace as the default delimiter. You can change that with useDelimiter See here: https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html

How to read in information from a file, and store it as a string. Java

ive gotten this far, but this doesnt work to read in the file, thats the part im stuck on. i know that you need to use the scanner, but im not sure what im missing here. i think it needs a path to the file also, but i dont know where to put that in
public class string
{
public static String getInput(Scanner in) throws IOException
{
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter file");
String filename =keyboard.next();
File inputFile = new File(filename);
Scanner input = new Scanner(inputFile);
String line;
while (input.hasNext())
{
line= input.nextLine();
System.out.println(line);
}
input.close();
}
if(filename.isEmpty())
{
System.out.println("Sorry, there has been an error. You must enter a string! (A string is some characters put together.) Try Again Below.");
return getInput(in);
}
else
{
return filename;
}
}
public static int getWordCount(String input)
{
String[] result = input.split(" ");
return result.length;
}
public static void main(String[] args)
{
DecimalFormat formatter = new DecimalFormat("0.##");
String input = getInput(new Scanner(System.in));
float counter = getWordCount(input);
System.out.println("The number of words in this string ("+input+") are: " + counter);
Scanner keyboard= new Scanner(System.in);
}
}
//end of code
First of all, when doing file I/O in Java, you should properly handle all exceptions and errors that can occur.
In general, you need to open streams and resources in a try block, catch all exceptions that happen in a catch block and then close all resources in a finally block. You should read up more on these here as well.
For using a Scanner object, this would look something like:
String token = null;
File file = null;
Scanner in = null;
try {
file = new File("/path/to/file.txt");
in = new Scanner(file);
while(in.hasNext()) {
token = in.next();
// ...
}
} catch (FileNotFoundException e) {
// if File with that pathname doesn't exist
e.printStackTrace();
} finally {
if(in != null) { // pay attention to NullPointerException possibility here
in.close();
}
}
You can also use a BufferedReader to read a file line by line.
BufferedReader reader = new BufferedReader(new FileReader("/path/to/file.txt"));
String line = null;
while ((line = reader.readLine()) != null) {
// ...
}
With added exception handling:
String line = null;
FileReader fReader = null;
BufferedReader bReader = null;
try {
fReader = new FileReader("/path/to/file.txt");
bReader = new BufferedReader(fReader);
while ((line = bReader.readLine()) != null) {
// ...
}
} catch (FileNotFoundException e) {
// Missing file for the FileReader
e.printStackTrace();
} catch (IOException e) {
// I/O Exception for the BufferedReader
e.printStackTrace();
} finally {
if(fReader != null) { // pay attention to NullPointerException possibility here
try {
fReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(bReader != null) { // pay attention to NullPointerException possibility here
try {
bReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
In general, use the Scanner for parsing a file, and use the BufferedReader for reading the file line by line.
There are other more advanced ways to perform reading/writing operations in Java. Check out some of them here

Load .text file in string array

How can I load .txt file into string array?
private void FileLoader() {
try {
File file = new File("/some.txt");
Scanner sc = new Scanner(new FileInputStream(file), "Windows-1251");
//Obviously, exception
int i = 0;
while (sc.hasNextLine()) {
morphBuffer[i] = sc.nextLine();
i++;
//Obviously, exception
}
sc.close();
} catch (FileNotFoundException e) {
JOptionPane.showMessageDialog(null, "File not found: " + e);
return;
}
}
There is an issue with array's length, because I don't know how long my array will be.
Of course i saw this question, but there is not an array of string. I need it, because I have to work with whole text, also with null strings.
How can I load a text file into string array?
Starting with Java 7, you can do it in a single line of code:
List<String> allLines = Files.readAllLines("/some.txt", Charset.forName("Cp1251"));
If you need your data in a string array rather than a List<String>, call toArray(new Strinf[0]) on the result of the readAllLines method:
String[] allLines = Files.readAllLines("/some.txt", Charset.forName("Cp1251")).toArray(new String[0]);
Use List
private void FileLoader() {
try {
File file = new File("/some.txt");
Scanner sc = new Scanner(new FileInputStream(file), "Windows-1251");
List<String> mylist = new ArrayList<String>();
while (sc.hasNextLine()) {
mylist.add(sc.nextLine());
}
sc.close();
} catch (FileNotFoundException e) {
JOptionPane.showMessageDialog(null, "File not found: " + e);
return;
}
}
You can use Collection ArrayList
while (sc.hasNextLine()) {
list.add(sc.nextLine());
i++;
//Obviously, exception
}
http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html

Categories

Resources