I'm new in Java.
I want to input a text file and create from it a two dimensional array the input is
like this
12,242 323,2324
23,4434 23,4534
23,434 56,3434
....
34,434 43,3443
I have tried
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
public class InputText {
/**
* #param args the command line arguments
* #throws java.io.IOException
*/
public static void main(String[] args) throws IOException {
int i=0;
File file;
file = new File("file.txt");
Scanner read=new Scanner(file);
while (read.hasNextLine()) {
String line=read.nextLine();
System.out.println(line);
}
}
}
which gives me the input but I cannot insert this in an array I tried different ways like splitting it.
Any suggestions?
Sorry for not being clear. The input i mentioned is doubles seperated by spaces. Also the format i gave you is what i get after i run the part of the programm i wrote. What i see in the text file is the numbers seperated by spaces. I tried to implement your suggestion but nothing seemed to work. I'm really lost here....
If you want to split a line to two numbers you can use
string[] numbers = line.split("\\s+");
If you want to read a double with comma
NumberFormat format = NumberFormat.getInstance(Locale.FRANCE);
...
double d1 = format.parse(numbers[0]).doubleValue();
double d2 = format.parse(numbers[1]).doubleValue();
Personally i prefer to use scanner. In that case create it with
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
Scanner scanner2 = new Scanner(scanner.nextLine()).useLocale(Locale.FRANCE);
if (!scanner2.hasNextDouble()){
System.out.println("Do not have a pair");
continue;
}
double d1 = scanner2.nextDouble();
if (!scanner2.hasNextDouble()){
System.out.println("Do not have a pair");
continue;
}
double d2 = scanner2.nextDouble();
//do something
}
After reading the line.. you will have to again split the string on ','. The split string need to be converted into interger. YOu can see as below:
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
public class InputText {
/**
* #param args the command line arguments
* #throws java.io.IOException
*/
public static void main(String[] args) throws IOException {
int i = 0;
File file;
file = new File("file.txt");
Scanner read = new Scanner(file);
while (read.hasNextLine()) {
String line = read.nextLine();
String[] numbers = line.split(",");
for (i = 0; i < numbers.lenght; i++) {
String numStr = numbers[i];
String x=numStr.replaceAll("\\s+",""); //eleminate the space in any.
Double num = Double.valueOf(x);
System.out.println(" num is: " + num); //Here you can store the number in array.
}
}
}
}
Try to use something like that(add also try catch statement)
String line = "";
br = new BufferedReader(new FileReader("file.txt"));
int i=0;
while ((line = br.readLine()) != null) {
// use comma as separator
String[] lineArray= line.split(",");
for(int j=0;j<lineArray.length;j++){
my2DArray[i][j] = lineArray[j];
}
i++;
}
for(int i=0;i<my2DArray[0].length;i++){
for(int j=0;j<my2DArray[1].length;j++){
System.out.print(my2DArray[i][j] + " ");
}
}
Related
it's showing null exception. what to do now?
import java.io.File;
import java.util.Scanner;
public class Quiz1 {
public static void main(String[] args) {
File f = new File("QuizMark.txt");
try{
Scanner s = new Scanner (f);
QuizMark[] p = new QuizMark[10];
while(s.hasNext()==true)
{
int c = s.nextInt();
double d = s.nextInt();
for(int i=0;i<10;i++){
p[i]= new QuizMark(c,d);
System.out.println(p[i].getId());
System.out.println(p[i].getScore());
i++;
}
}
}
catch(Exception e){
System.out.println(e.getMessage());
}
}
}
First of all your file must define a pattern of data saved in it like marks and id Separated by commas or hyphens underscores etc whatever you like to save pattern.Each next data should be on next line.Then read the text in proper manner as you saved in file.
Example QuizMarks.txt
01,96.5
02,78.9
03,65
04,89.7
Java Code
int count = 0;
String s[];
String line="";
QuizMark[] p = new QuizMark[10];
BufferedReader br= new BufferedReader(new FileReader("QuizMark.txt"));
while(line=br.readLine()!=null){
s=line.split(",");//your data separated by symbol in file
//First Record with id and marks
int id =Interger.parseInt(s[0]); //conversion from string to int
double marks = Double.parseDouble(s[1]); //conversion from string to double
p[count]= new QuizMark(id,marks);
count++;
}
This is my first post, so i'm not sure how things work here.
Basically, i need some help/advice with my code. The method need to read a certain line and print out the text after the inputted text and =
The text file would like
A = Ant
B = Bird
C = Cat
So if the user it input "A" it should print out something like
-Ant
So far, i manage to make it ignore "=" but still print out the whole file
here is my code:
public static void readFromFile() {
System.out.println("Type in your word");
Scanner scanner = new Scanner(System.in);
String input = scanner.next();
String output = "";
try {
FileReader fr = new FileReader("dictionary.txt");
BufferedReader br = new BufferedReader(fr);
String[] fields;
String temp;
while((input = br.readLine()) != null) {
temp = input.trim();
if (temp.startsWith(input)) {
String[] splitted = temp.split("=");
output += splitted[1] + "\n";
}
}
System.out.print("-"+output);
}
catch(IOException e) {
}
}
It looks like this line is the problem, as it will always be true.
if (temp.startsWith(input))
You need to have a different variables for the lines being read out of the file and for the input you're holding from the user. Try something like:
String fileLine;
while((fileLine = br.readLine()) != null)
{
temp = fileLine.trim();
if (temp.startsWith(input))
{
String[] splitted = temp.split("=");
output += splitted[1] + "\n";
}
}
You can use useDelimiter() method of Scanner to split input text
scanner.useDelimiter("(.)*="); // Matches 0 or more characters followed by '=', and then gives you what is after `=`
The following code is something I've tried in IDEONE (http://ideone.com/TBwCFj)
Scanner s = new Scanner(System.in);
s.useDelimiter("(.)*=");
while(s.hasNext())
{
String ss = s.next();
System.out.print(ss);
}
/**
* Output
*
*/
Ant
Bat
You need to first split the text file by new line "\n" (assuming after each "A = Ant", "B = Bird" ,"C = Cat" declaration it starts with a new line) and THEN locate the inputted character and further split that by "=" as you were doing.
So you will need two arrays of Strings (String[ ]) one for each line and one for the separation of each line into e.g. "A" and "Ant".
You are very close.
try this, it works: STEPS:
1) read input using scanner
2) read file using bufferedreader
3) split each line using "-" as a delimiter
4) compare first character of line with input
5) if first character is equal to input then print the associated value, preceded by a "-"
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.File;
import java.util.Scanner;
class myRead{
public static void main(String[] args) throws FileNotFoundException, IOException {
System.out.println("Type in your word");
Scanner scanner = new Scanner(System.in);
String input = scanner.next();
long numberOfLines = 0;
BufferedReader myReader = new BufferedReader(new FileReader("test.txt"));
String line = myReader.readLine();
while(line != null){
String[] parts = line.split("=");
if (parts[0].trim().equals(input.trim())) {
System.out.println("-"+parts[1]);
}
line = myReader.readLine();
}
}
}
OUTPUT (DEPENDING ON INPUT):
- Ant
- Bird
- Cat
I have this block of code:
import java.util.*;
import java.io.*;
class Problem
{
public static void main (String[] args) throws IOException
{
Scanner file = new Scanner( new File( "file.dat" ) );
int times = file.nextInt();
file.nextLine();
for( int zz = 0; zz < times; zz++ )
{
???
}
}
}
The goal is to read in lines from file.dat (pre-provided), and then output the number of digits on a line that was read in. However, whenever I put int[] array = {file.nextLine}; in the space under the for loop, it doesn't run. Am I doing something wrong?
Why don't you use BufferedReader instead:
file = new BufferedReader(new FileReader("file.dat"));
while ((line = br.readLine()) != null) {
System.out.println(line.split("\\s+").length);
}
split() returns a String[] and you just use its array length
Im probably going around this the wrong way, but My question is, how would I go about filling the array for fxRates?
CAD,EUR,GBP,USD
1.0,0.624514066,0.588714763,0.810307
1.601244959,1.0,0.942676548,1.2975
1.698615463,1.060809248,1.0,1.3764
1.234100162,0.772200772,.726532984,1.0
This is the information i have in the CSV file, I was thinking about using the scanner class to read it. Something like
private double[][] fxRates;
String delimiter = ","
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
String line = sc.nextLine();
fxRates = line.split(delimiter)
Your way of solving this problem seems OK. But line.split(",") will return a 1D String array. You cannot assign it to fxRates. And also you should know the number of lines or rows in order to initialize fxRates at the beginning. Otherwise you should use a dynamic list structure like ArrayList.
Supposing you have 50 lines in your file, you can use something like:
private String[][] fxRates = String[50][];
String delimiter = ",";
Scanner sc = new Scanner(file);
int index=0;
while (sc.hasNextLine())
{
String line = sc.nextLine();
fxRates[index++] = line.split(delimiter)
}
And note that I've declared fxRates as a 2D String array, if you need double values you should do some conversion in place or later on.
import java.nio.charset.Charset;
import java.nio.file.Paths;
import java.nio.file.Files;
import java.io.IOException;
public class CSVReader{
private String readFile(String path, Charset encoding) throws IOException
{
//Read in all bytes from a file at the specified path into a byte array
//This method will fail if there is no file to read at the specified path
byte[] encoded = Files.readAllBytes(Paths.get(path));
//Convert the array of bytes into a string.
return new String(encoded, encoding);
}
public String readFile(String path)
{
try {
//Read the contents of the file at the specified path into one long String
String content = readFile(path, Charset.defaultCharset());
//Display the string. Feel free to comment this line out.
System.out.println("File contents:\n"+content+"\n\n");
//Return the string to caller
return content;
}catch (IOException e){
//This code will only execute if we could not open a file
//Display the error message
System.out.println("Cannot read file "+path);
System.out.println("Make sure the file exists and the path is correct");
//Exit the program
System.exit(1);
}`enter code here`
return null;
}
}
The result of a split operation is a String array, not an array of double. So one step is missing: converting the Strings to doubles:
private double[][] fxRates = new double[maxLines][4];
String delimiter = ","
int line = 0;
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
String line = sc.nextLine();
String[] fxRatesAsString = line.split(delimiter);
for (int i = 0; i < fxRatesAsString.length; i++) {
fxRates[line][i] = Double.parseDouble(fxRatesAsString[i]);
}
Another example;
Double[][] fxRates = new Double[4][];
String delimiter = ",";
//file code goes here
Scanner sc = new Scanner(file);
// Read File Line By Line
int auxI = 0;
// Read File Line By Line
for (int auxI =0; sc.hasNextLine(); auxI++) {
String line = sc.nextLine();
System.out.println(line);
String[] fxRatesAsString = line.split(delimiter);
Double[] fxRatesAsDouble = new Double[fxRatesAsString.length];
for (int i = 0; i < fxRatesAsString.length; i++) {
fxRatesAsDouble[i] = Double.parseDouble(fxRatesAsString[i]);
}
fxRates[auxI] = fxRatesAsDouble;
}
//to double check it
for (int y =0; y<fxRates.length; y++){
for (int x =0; x<fxRates.length; x++){
System.out.print(fxRates[y][x] +" ");
}
System.out.println("");
}
I wouldn't recommend you to parse CSVs in such a way, because Scanner is too low-level and raw solution for this. In comparison, DOM/SAX parsers are better to parse XML rather than regular expressions parsing or whatever that does not consider the document structure. There are CSV parsers that feature good APIs and suggest configuration options during a reader initialization. Just take a look at easy to use CsvReader. Here is a code sample using it:
package q12967756;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Collection;
import static java.lang.Double.parseDouble;
import static java.lang.System.out;
import com.csvreader.CsvReader;
public final class Main {
private Main() {
}
private static final String MOCK =
"CAD,EUR,GBP,USD\n" +
"1.0,0.624514066,0.588714763,0.810307\n" +
"1.601244959,1.0,0.942676548,1.2975\n" +
"1.698615463,1.060809248,1.0,1.3764\n" +
"1.234100162,0.772200772,.726532984,1.0\n";
private static final char SEPARATOR = ',';
public static void main(String[] args) throws IOException {
// final FileReader contentReader = new FileReader("yourfile.csv");
final StringReader contentReader = new StringReader(MOCK);
final CsvReader csv = new CsvReader(contentReader, SEPARATOR);
csv.readHeaders(); // to skip `CAD,EUR,GBP,USD`
final Collection<double[]> temp = new ArrayList<double[]>();
while ( csv.readRecord() ) {
temp.add(parseRawValues(csv.getValues()));
}
final double[][] array2d = temp.toArray(new double[temp.size()][]);
out.println(array2d[3][1]);
}
private static double[] parseRawValues(String[] rawValues) {
final int length = rawValues.length;
final double[] values = new double[length];
for ( int i = 0; i < length; i++ ) {
values[i] = parseDouble(rawValues[i]);
}
return values;
}
}
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();
}