I have a .csv file which has header that I would like to be skipped. I get error when the header is present in the .csv file but when it is removed program runs perfectly fine. I would like my code to skip the header and continue on with the process.
What the .csv files looks like:
Make Model Speed Fuel BaseMPG ScaleFactor Time Travelled
Ford Mustang 0 20.2 20 0.02 2.3
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Test {
public static void main(String[] args) throws IOException {
List<Vehicle> cars = new ArrayList<Vehicle>();
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the file name:");
String filename = scanner.nextLine();
BufferedReader reader = new BufferedReader(new FileReader(new File(
filename.trim())));
String line = "";
while ((line = reader.readLine()) != null) {
String[] words = line.split(",");
String make = words[0];
String model = words[1];
int currentSpeed = Integer.parseInt(words[2]);
double fuel = Double.parseDouble(words[3]);
double baseMpg = Double.parseDouble(words[4]);
double scaleFactor = Double.parseDouble(words[5]);
double timeTravelled = Double.parseDouble(words[6]);
Vehicle car = new Car(fuel, currentSpeed, baseMpg, scaleFactor,
make, model, timeTravelled);
System.out.println(car);
cars.add(car);
}
FileWriter writer=new FileWriter(new File("ProcessedCars.txt"));
for(Vehicle car:cars)
{
writer.write(car.toString());
writer.flush();
writer.write("\r\n");
}
}
}
Skip the first line in your while loop:
boolean skip = true;
while ((line = reader.readLine()) != null) {
if(skip) {
skip = false; // Skip only the first line
continue;
}
String[] words = line.split(",");
// ...
}
One way to do it is to catch the exception:
try{
int currentSpeed = Integer.parseInt(words[2]);
// ...
}catch(NumberFormatException e){
// Failed to parse speed, input is likely a text, like header
}
Or, if you are sure there is a header, just call an extra readline() before your loop.
Related
I have code that is supposed to receive a filename from the user and output the contents in a numbered list like this:
https://imgur.com/a/CGd86xU
Now, I can't seem to be able to add the 1. 2. 3., etc into my output without hardcoding, or how I can try to detect if a file isn't found in the same directory as the code file is in and tell the user such file doesn't exist.
So far the code that I have output the code correctly as shown in the example but minus the numbering the content of the files or distinguishing if the file the user inputs exists.
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class Q4 {
public static void main(String[] args) throws IOException {
try {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter filename");
String fileName = scanner.nextLine();
File f = new File(fileName);
BufferedReader b = new BufferedReader(new FileReader(f));
String readLine = null;
System.out.println(""); //Intended to be empty as to allow the next line. So far that's the only way to get this part it to work.
while ((readLine = b.readLine()) != null) {
System.out.println(readLine);
}
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
Note: I'm rather new to code involving files so yeah...
If I understand what you're asking correctly, you want to print line numbers for each line of the file specified by the user.
If so, then you can just add a counter variable when you read the file line by line:
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class Q4 {
public static void main(String[] args) throws IOException {
try {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter filename");
String fileName = scanner.nextLine();
File f = new File(fileName);
if (!f.exists()) {
System.out.println(fileName + " doesn't exist!");
return;
}
BufferedReader b = new BufferedReader(new FileReader(f));
String readLine = null;
System.out.println(""); //Intended to be empty as to allow the next line. So far that's the only way to get this part it to work.
int counter = 1;
while ((readLine = b.readLine()) != null) {
System.out.println(counter + ": " + readLine);
counter++;
}
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
I also added a check to see if the File exists using the File.exists() method.
This a program which presents how many times does each word occur within a text file. what is going on is that its also picking up characters like ? and , i only want it to pick letters. This is just part of the results {"1"=1, "Cheers"=1, "Fanny"=1, "I=1, "biscuits"=1, "chairz")=1, "cheeahz"=1, "crisps"=1, "jumpers"=1, ?=20, work:=1
import java.io.File;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.TreeMap;
import java.util.StringTokenizer;
public class Unigrammodel {
public static void main(String [] args){
//Creating BufferedReader to accept the file name from the user
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String fileName = null;
System.out.print("Please enter the file name with path: ");
try{
fileName = (String) br.readLine();
//Creating the BufferedReader to read the file
File textFile = new File(fileName);
BufferedReader input = new BufferedReader(new FileReader(textFile));
//Creating the Map to store the words and their occurrences
TreeMap<String, Integer> frequencyMap = new TreeMap<String, Integer>();
String currentLine = null;
//Reading line by line from the text file
while((currentLine = input.readLine()) != null){
//Parsing the words from each line
StringTokenizer parser = new StringTokenizer(currentLine);
while(parser.hasMoreTokens()){
String currentWord = parser.nextToken();
//remove all non-alphanumeric from this word
currentWord.replaceAll(("[^A-Za-z0-9 ]"), "");
Integer frequency = frequencyMap.get(currentWord);
if(frequency == null){
frequency = 0;
}
//Putting each word and its occurrence into Map
frequencyMap.put(currentWord, frequency + 1);
}
}
//Displaying the Result
System.out.println(frequencyMap +"\n");
}catch(IOException ie){
ie.printStackTrace();
System.err.println("Your entered path is wrong");
}
}
}
Strings are immutable, so you need to assign the modified string to a variable before adding it to the map.
String wordCleaned= currentWord.replaceAll(("[^A-Za-z0-9 ]"), "");
...
frequencyMap.put(wordCleaned, frequency + 1);
I have many text files (up to 20) and each file has it's contents like this
21.0|11|1/1/1997
13.3|12|2/1/1997
14.6|9|3/1/1997
and every file has approximately more than 300 lines.
so the problem I'm facing is this, how can I extract all and only the first values
of the file's content.
for example I want to extract the values (21.0,13.3,14.6.....etc) so I can decide the max number and minimum in all of the 20 files.
I have wrote this code from my understanding to experience it on of the files
but it didn't work
String inputFileName = "Date.txt";
File inputFile = new File(inputFileName);
Scanner input = new Scanner(inputFile);
int count = 0;
while (input.hasNext()){
double line = input.nextDouble(); //Error occurs "Exception in thread "main" java.util.InputMismatchException"
count++;
double [] lineArray= new double [365];
lineArray[count]= line;
System.out.println(count);
for (double s : lineArray){
System.out.println(s);
System.out.println(count);
and this one too
String inputFileName = "Date.txt";
File inputFile = new File(inputFileName);
Scanner input = new Scanner(inputFile);
while (input.hasNext()){
String line = input.nextLine();
String [] lineArray = line.split("//|");
for (String s : lineArray){
System.out.println(s+" ");
}
Note: I'm still kind of a beginner in Java
I hope I was clear and thanks
For each line of text, check whether it contains the pipe character. If it does, grab the first portion of the text and parse it to double.
double val = 0.0;
Scanner fScn = new Scanner(new File(“date.txt”));
while(fScn.hasNextLine()){ //Can also use a BufferedReader
data = fScn.nextLine();
if(data.contains("|")) //Ensure line contains "|"
val = Double.parseDouble(data.substring(0, data.indexOf("|"))); //grab value
}
Or you could try some streams, cool stuff
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class MinMaxPrinter {
public static void main(String[] args) {
final List<String> files = Arrays.asList("file", "names", "that", "you", "need");
new MinMaxPrinter().printMinMax(files);
}
public void printMinMax(List<String> fileNames) {
List<Double> numbers = fileNames.stream()
.map(Paths::get)
.flatMap(this::toLines)
.map(line -> line.split("\\|")[0])
.map(Double::parseDouble)
.collect(Collectors.toList());
double max = numbers.stream().max(Double::compare).get();
double min = numbers.stream().min(Double::compare).get();
System.out.println("Min: " + min + " Max: " + max);
}
private Stream<String> toLines(Path path) {
try {
return Files.lines(path);
} catch (IOException e) {
return Stream.empty();
}
}
}
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
while ((line = br.readLine()) != null) {
String res = s.split("\\|")[0];
}
}
As in the tittle , i want to write my text from back and enter to the text file . In first , i read the text from the text file , next i want to save it in text file , but writing by the end of. I don't have any ideas how to fix my code . My code read the text file , and write the text file , but in the same order , from beginning to ending.
Example how it must work:
input text:
aaaaa
bbbb
ccc
dd
f
output text:
f
dd
ccc
bbbb
aaaaa
My code:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
public class Loading {
public static void main(String[] args) {
try {
BufferedReader br = new BufferedReader(new FileReader(
"file.txt.txt"));
String line, txt = "";
String[] splittedLine;
while ((line = br.readLine()) != null) {
txt += linia + "\n";
splittedLine = line.split(" ");
}
System.out.println(txt);
br.close();
BufferedWriter bw = new BufferedWriter(new FileWriter("file2"));
bw.write(txt);
bw.newLine();
bw.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Read File to String
Write String data to File starting from end.
For lines, use String array to store data from file and then traverse from end to start of array.
Here is complete program.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.List;
public class Loading {
public static void main(String[] args) {
try {
BufferedReader br = new BufferedReader(new FileReader(
"DB.xml"));
String line, txt = "";
List<String> lines = new ArrayList<String>();
while ((line = br.readLine()) != null) {
lines.add(line);
}
System.out.println(txt);
br.close();
BufferedWriter bw = new BufferedWriter(new FileWriter("file2"));
for(int i=lines.size()-1; i>=0; i--){
bw.write(lines.get(i));
bw.newLine();
}
bw.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
You're going to want a list of lines, since you don't know the number of entries beforehand, so you want something that can grow with your code.
List<String> lines = new ArrayList<String>();
And add all your lines to it
while ((line = br.readLine()) != null) {
lines.add(line);
}
Then write them to your file in reverse order:
for(int i = lines.size() - 1; i >= 0; i--) {
bw.write(lines.get(i));
bw.newLine();
}
Your code is concatenating the string incorrectly. It needs to add the line text to the beginning of the string rather than at the end if you are trying to reverse the order.
txt = line + txt + "\n"; //original: txt += linia + "\n"
But it would be better to use a StringBuilder object to handle the concatenation for you. Something like...
StringBuilder txt = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
txt.insert(0, line + "\n");
}
System.out.println(txt.toString());
I do agree that the array approach in the other answers would also work and is probably a little easier to read and maintain. But the StringBuilder approach is closer to what you already have.
It should work:
package test;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
/**
*
* #author
*/
public class Read {
public static void main(String[] args) {
try {
BufferedReader br = new BufferedReader(new FileReader(
"D:/file.txt"));
String line, txt = "";
ArrayList<String> lines = new ArrayList<String>();
while ((line = br.readLine()) != null) {
lines.add(line);
}
System.out.println(txt);
br.close();
BufferedWriter bw = new BufferedWriter(new FileWriter("D:/file2.txt"));
for(int i = lines.size()-1; i>=0; i--){
bw.write(lines.get(i));
bw.newLine();
}
bw.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
i'm doing tokenizing a text file in java. I want to read an input file, tokenize it and write a certain character that has been tokenized into an output file. This is what i've done so far:
package org.apache.lucene.analysis;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StreamTokenizer;
class StringProcessing {
// Create BufferedReader class instance
public static void main(String[] args) throws IOException {
InputStreamReader input = new InputStreamReader(System.in);
BufferedReader keyboardInput = new BufferedReader(input);
System.out.print("Please enter a java file name: ");
String filename = keyboardInput.readLine();
if (!filename.endsWith(".DAT")) {
System.out.println("This is not a DAT file.");
System.exit(0);
}
File File = new File(filename);
if (File.exists()) {
FileReader file = new FileReader(filename);
StreamTokenizer streamTokenizer = new StreamTokenizer(file);
int i = 0;
int numberOfTokensGenerated = 0;
while (i != StreamTokenizer.TT_EOF) {
i = streamTokenizer.nextToken();
numberOfTokensGenerated++;
}
// Output number of characters in the line
System.out.println("Number of tokens = " + numberOfTokensGenerated);
// Output tokens
for (int counter = 0; counter < numberOfTokensGenerated; counter++) {
char character = file.toString().charAt(counter);
if (character == ' ') { System.out.println(); } else { System.out.print(character); }
}
} else {
System.out.println("File does not exist!");
System.exit(0);
}
System.out.println("\n");
}//end main
}//end class
When i run this code, this is what i get:
Please enter a java file name: D://eclipse-java-helios-SR1-win32/LexractData.DAT
Number of tokens = 129
java.io.FileReader#19821fException in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 25
at java.lang.String.charAt(Unknown Source)
at org.apache.lucene.analysis.StringProcessing.main(StringProcessing.java:40)
The input file will look like this:
-K1 Account
--Op1 withdraw
---Param1 an
----Type Int
---Param2 amount
----Type Int
--Op2 deposit
---Param1 an
----Type Int
---Param2 Amount
----Type Int
--CA1 acNo
---Type Int
-K2 CheckAccount
--SC Account
--CA1 credit_limit
---Type Int
-K3 Customer
--CA1 name
---Type String
-K4 Transaction
--CA1 date
---Type Date
--CA2 time
---Type Time
-K5 CheckBook
-K6 Check
-K7 BalanceAccount
--SC Account
I just want to read the string which are starts with -K1, -K2, -K3, and so on... can anyone help me?
The problem is with this line --
char character = file.toString().charAt(counter);
file is a reference to a FileReader that does not implement toString() .. it calls Object.toString() which prints a reference around 25 characters long. Thats why your exception says OutofBoundsException at the 26th character.
To read the file correctly, you should wrap your filereader with a bufferedreader and then put each readline into a stringbuffer.
FileReader fr = new FileReader(filename);
BufferedReader br = new BufferedReader(fr);
StringBuilder sb = new StringBuilder();
String s;
while((s = br.readLine()) != null) {
sb.append(s);
}
// Now use sb.toString() instead of file.toString()
If you are wanting to tokenize the input file then the obvious choice is to use a Scanner. The Scanner class reads a given input stream, and can output either tokens or other scanned types (scanner.nextInt(), scanner.nextLine(), etc).
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(new File("filename.dat"));
while (in.hasNext) {
String s = in.next(); //get the next token in the file
// Now s contains a token from the file
}
}
Check out Oracle's documentation of the Scanner class for more info.
public class FileTokenize {
public static void main(String[] args) throws IOException {
final var lines = Files.readAllLines(Path.of("myfile.txt"));
FileWriter writer = new FileWriter( "output.txt");
String data = " ";
for (int i = 0; i < lines.size(); i++) {
data = lines.get(i);
StringTokenizer token = new StringTokenizer(data);
while (token.hasMoreElements()) {
writer.write(token.nextToken() + "\n");
}
}
writer.close();
}