[EDITED} Ok I get it, let me reformulate. numVol is 45 and the contents of the file is
54;a;23;c;de;56
23;d;24;c;h;456
45;87;c;y;535
432;42;h;h;543
but I still can't fix my problem, with this it return 543. so what im trying to do is return line when its equals numVol but check only the first number of a line.
I'm having trouble comparing two strings. Let's say I have a .csv file with the following content: 54;a;b;c;de and that numVol value is 54. the method should be returning 54 but for some reason it doesnt enter in the "if" and it return "de".
public static String test(int numVol)throws Exception{
File file = new File("test.csv");
Scanner scanner = new Scanner(file);
scanner.useDelimiter(";");
String line = "";
String sNumVol = ""+numVol; //create a string with numVol value in it
while (scanner.hasNext()){
line = scanner.next();
if(line.equals(sNumVol)){
scanner.close();
return line;
}
}
scanner.close();
return line;
}
The problem is that now that you've told Scanner to use ; as a delimiter, it's not using whitespace as a delimiter anymore. So the token being tested against "45" isn't "45", it's "456\n45" (the end of the previous line, the newline, and the beginning of the next line), which isn't a match.
Change your useDelimiter line to use both semicolons and whitespace as your delimiters:
scanner.useDelimiter("[;\\s]");
...and then the scanner sees the "456" and the "45" separately, and matches the "45".
This code:
import java.util.*;
import java.io.*;
public class Parse {
public static final void main(String[] args) {
try {
String result = test(45);
System.out.println("result = " + result);
}
catch (Exception e) {
System.out.println("Exception");
}
}
public static String test(int numVol)throws Exception{
File file = new File("test.csv");
Scanner scanner = new Scanner(file);
scanner.useDelimiter("[;\\s]"); // <==== Change is here
String line = "";
String sNumVol = ""+numVol;
while (scanner.hasNext()){
line = scanner.next();
if(line.equals(sNumVol)){
scanner.close();
return line;
}
}
scanner.close();
return line;
}
}
With this test.csv:
54;a;23;c;de;56
23;d;24;c;h;456
45;87;c;y;535
432;42;h;h;543
Shows this:
$ java Parse
result = 45
The way to find the answer to this problem was simply to walk through the code with a debugger and watch the value of line, or (if for some reason you don't have a debugger?!), insert a System.out.println("line = " + line); statement into the loop to see what was being compared. For instance, if you insert a System.out.println("line = " + line); above the line = scanner.next(); line above and you just use ";" as the delimiter:
import java.util.*;
import java.io.*;
public class Parse {
public static final void main(String[] args) {
try {
String result = test(45);
System.out.println("result = " + result);
}
catch (Exception e) {
System.out.println("Exception");
}
}
public static String test(int numVol)throws Exception{
File file = new File("test.csv");
Scanner scanner = new Scanner(file);
scanner.useDelimiter(";"); // <== Just using ";"
String line = "";
String sNumVol = ""+numVol;
while (scanner.hasNext()){
line = scanner.next();
System.out.println("line = [[" + line + "]]");
if(line.equals(sNumVol)){
scanner.close();
return line;
}
}
scanner.close();
return line;
}
}
You see this:
$ java Parse
line = [[54]]
line = [[a]]
line = [[23]]
line = [[c]]
line = [[de]]
line = [[56
23]]
line = [[d]]
line = [[24]]
line = [[c]]
line = [[h]]
line = [[456
45]]
line = [[87]]
line = [[c]]
line = [[y]]
line = [[535
432]]
line = [[42]]
line = [[h]]
line = [[h]]
line = [[543
]]
result = 543
...which helps visualize the problem.
Related
I'm printing the difference between long numbers from a file and I'm listing the results within a loop. But I don't want to print the newline for the last result that gets printed.
Here's the code that prints the results :
public static void main(String[] args) {
Scanner sc;
long a = 0, b = 0;
try {
Scanner input = new Scanner(System.in);
File file = new File(input.nextLine());
input = new Scanner(file);
while (input.hasNextLine()) {
String line = input.nextLine();
String split[] = line.split("\\s+");
a = Long.parseLong(split[0]);
b = Long.parseLong(split[1]);
System.out.println(Math.abs(a-b));
}
input.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
System.out.println(e.getMessage());
}
The output which I get now is :
2
71293781685339
12345677654320
and this has a newline in the end.
How do I avoid the new line while printing last result? Any ideas?
You can check if there is still input left to be processed before printing a new line
while (input.hasNextLine()) {
String line = input.nextLine();
String split[] = line.split("\\s+");
a = Long.parseLong(split[0]);
b = Long.parseLong(split[1]);
System.out.print(Math.abs(a-b)); //Print without a newline
if (input.hasNextLine()) {
System.out.println();//Print new line if there is more input left
}
}
Print the first line using System.out.println(line), and print the rest lines using System.out.print("\n" + line).
I am trying to read data from a text file and then store it to an array. I assume that there is one word per line. I am getting a NoSuchElementException here:
while (s.hasNextLine())
{
text = text + s.next() + " ";
}
This is my code:
public class ReadNote
{
public static void main(String[]args)
{
String text = readString("CountryList.txt");
System.out.println(text);
String[] words = readArray("CountryList.txt");
for (int i = 0; i < words.length; i++)
{
System.out.println(words[i]);
}
}
public static String readString(String file)
{
String text = "";
try{
Scanner s = new Scanner(new File(file));
while (s.hasNextLine())
{
text = text + s.next() + " ";
}
} catch(FileNotFoundException e)
{
System.out.println("file not found ");
}
return text;
}
public static String[] readArray(String file)
{
int ctr = 0;
try {
Scanner s1 = new Scanner(new File(file));
while (s1.hasNextLine())
{
ctr = ctr+1;
s1.next();
}
String[] words = new String[ctr];
Scanner s2 = new Scanner(new File(file));
for ( int i = 0; i < ctr; i++)
{
words [i] = s2.next();
}
return words;
} catch (FileNotFoundException e) { }
return null;
}
}
Here is the message.
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1371)
at ReadNote.readString(ReadNote.java:29)
at ReadNote.main(ReadNote.java:13)
For the specific exception you are getting in readString:
while (s.hasNextLine()) {
text = text + s.next() + " ";
}
You need to either call s.hasNext() in the loop guard, or use s.nextLine() in the body.
As described in this answer.
You have a single extra newline at the end of your file.
hasNextLine() checks to see if there is another linePattern in the buffer.
hasNext() checks to see if there is a parseable token in the buffer, as separated by the scanner's delimiter.
You should modify your code to one of the following
while (s.hasNext()) {
text = text + s.next() + " ";
}
while (s.hasNextLine()) {
text = text + s.nextLine() + " ";
}
There are 2 issues with your code as far as I can tell:
You forgot to check hasNextLine() for your second Scanner s2.
When using Scanner you need to check if there is a next line with hasNextLine(), and it will return null at EOF.
You probably want s.nextLine() instead of s.next() in your while loop since you are checking while (s1.hasNextLine()). In general, you have to match your .hasNext... to your .next....
I am have a project that need to modify some text in the text file.
Like BB,BO,BR,BZ,CL,VE-BR
I need make it become BB,BO,BZ,CL,VE.
and HU, LT, LV, UA, PT-PT/AR become HU, LT, LV, UA,/AR.
I have tried to type some code, however the code fail to loop and also,in this case.
IN/CI, GH, KE, NA, NG, SH, ZW /EE, HU, LT, LV, UA,/AR, BB
"AR, BB,BO,BR,BZ,CL, CO, CR, CW, DM, DO,VE-AR-BR-MX"
I want to delete the AR in second row, but it just delete the AR in first row.
I got no idea and seeking for helps.
Please
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.util.Scanner;
public class tomy {
static StringBuffer stringBufferOfData = new StringBuffer();
static StringBuffer stringBufferOfData1 = stringBufferOfData;
static String filename = null;
static String input = null;
static String s = "-";
static Scanner sc = new Scanner(s);
public static void main(String[] args) {
boolean fileRead = readFile();
if (fileRead) {
replacement();
writeToFile();
}
System.exit(0);
}
private static boolean readFile() {
System.out.println("Please enter your files name and path i.e C:\\test.txt: ");
filename = "C:\\test.txt";
Scanner fileToRead = null;
try {
fileToRead = new Scanner(new File(filename));
for (String line; fileToRead.hasNextLine()
&& (line = fileToRead.nextLine()) != null;) {
System.out.println(line);
stringBufferOfData.append(line).append("\r\n");
}
fileToRead.close();
return true;
} catch (FileNotFoundException ex) {
System.out.println("The file " + filename + " could not be found! "+ ex.getMessage());
return false;
} finally {
fileToRead.close();
return true;
}
}
private static void writeToFile() {
try {
BufferedWriter bufwriter = new BufferedWriter(new FileWriter(
filename));
bufwriter.write(stringBufferOfData.toString());
bufwriter.close();
} catch (Exception e) {// if an exception occurs
System.out.println("Error occured while attempting to write to file: "+ e.getMessage());
}
}
private static void replacement() {
System.out.println("Please enter the contents of a line you would like to edit: ");
String lineToEdit = sc.nextLine();
int startIndex = stringBufferOfData.indexOf(lineToEdit);
int endIndex = startIndex + lineToEdit.length() + 2;
String getdata = stringBufferOfData.substring(startIndex + 1, endIndex);
String data = " ";
Scanner sc1 = new Scanner(getdata);
Scanner sc2 = new Scanner(data);
String lineToEdit1 = sc1.nextLine();
String replacementText1 = sc2.nextLine();
int startIndex1 = stringBufferOfData.indexOf(lineToEdit1);
int endIndex1 = startIndex1 + lineToEdit1.length() + 3;
boolean test = lineToEdit.contains(getdata);
boolean testh = lineToEdit.contains("-");
System.out.println(startIndex);
if (testh = true) {
stringBufferOfData.replace(startIndex, endIndex, replacementText1);
stringBufferOfData.replace(startIndex1, endIndex1 - 2,
replacementText1);
System.out.println("Here is the new edited text:\n"
+ stringBufferOfData);
} else {
System.out.println("nth" + stringBufferOfData);
System.out.println(getdata);
}
}
}
I wrote a quick method for you that I think does what you want, i.e. remove all occurrences of a token in a line, where that token is embedded in the line and is identified by a leading dash.
The method reads the file and writes it straight out to a file after editing for the token. This would allow you to process a huge file without worrying about about memory constraints.
You can simply rename the output file after a successful edit. I'll leave it up to you to work that out.
If you feel you really must use string buffers to do in memory management, then grab the logic for the line editing from my method and modify it to work with string buffers.
static void onePassReadEditWrite(final String inputFilePath, final String outputPath)
{
// the input file
Scanner inputScanner = null;
// output file
FileWriter outputWriter = null;
try
{
// open the input file
inputScanner = new Scanner(new File(inputFilePath));
// open output file
File outputFile = new File(outputPath);
outputFile.createNewFile();
outputWriter = new FileWriter(outputFile);
try
{
for (
String lineToEdit = inputScanner.nextLine();
/*
* NOTE: when this loop attempts to read beyond EOF it will throw the
* java.util.NoSuchElementException exception which is caught in the
* containing try/catch block.
*
* As such there is NO predicate required for this loop.
*/;
lineToEdit = inputScanner.nextLine()
)
// scan all lines from input file
{
System.out.println("START LINE [" + lineToEdit + "]");
// get position of dash in line
int dashInLinePosition = lineToEdit.indexOf('-');
while (dashInLinePosition != -1)
// this line has needs editing
{
// split line on dash
String halfLeft = lineToEdit.substring(0, dashInLinePosition);
String halfRight = lineToEdit.substring(dashInLinePosition + 1);
// get token after dash that is to be removed from whole line
String tokenToRemove = halfRight.substring(0, 2);
// reconstruct line from the 2 halves without the dash
StringBuilder sb = new StringBuilder(halfLeft);
sb.append(halfRight.substring(0));
lineToEdit = sb.toString();
// get position of first token in line
int tokenInLinePosition = lineToEdit.indexOf(tokenToRemove);
while (tokenInLinePosition != -1)
// do for all tokens in line
{
// split line around token to be removed
String partLeft = lineToEdit.substring(0, tokenInLinePosition);
String partRight = lineToEdit.substring(tokenInLinePosition + tokenToRemove.length());
if ((!partRight.isEmpty()) && (partRight.charAt(0) == ','))
// remove prefix comma from right part
{
partRight = partRight.substring(1);
}
// reconstruct line from the left and right parts
sb.setLength(0);
sb = new StringBuilder(partLeft);
sb.append(partRight);
lineToEdit = sb.toString();
// find next token to be removed from line
tokenInLinePosition = lineToEdit.indexOf(tokenToRemove);
}
// handle additional dashes in line
dashInLinePosition = lineToEdit.indexOf('-');
}
System.out.println("FINAL LINE [" + lineToEdit + "]");
// write line to output file
outputWriter.write(lineToEdit);
outputWriter.write("\r\n");
}
}
catch (java.util.NoSuchElementException e)
// end of scan
{
}
finally
// housekeeping
{
outputWriter.close();
inputScanner.close();
}
}
catch(FileNotFoundException e)
{
e.printStackTrace();
}
catch(IOException e)
{
inputScanner.close();
e.printStackTrace();
}
}
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
Can any one suggest, how to use string-tokens in java, to read all data in a file, and display only some of its contents. Like, if i have
apple = 23456, mango = 12345, orange= 76548, guava = 56734
I need to select apple, and the value corresponding to apple should be displayed in the output.
This is the code
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.StringTokenizer;
public class ReadFile {
public static void main(String[] args) {
try {
String csvFile = "Data.txt";
//create BufferedReader to read csv file
BufferedReader br = new BufferedReader(new FileReader(csvFile));
String line = "";
StringTokenizer st = null;
int lineNumber = 0;
int tokenNumber = 0;
//read comma separated file line by line
while ((line = br.readLine()) != null) {
lineNumber++;
//use comma as token separator
st = new StringTokenizer(line, ",");
while (st.hasMoreTokens()) {
tokenNumber++;
//display csv values
System.out.print(st.nextToken() + " ");
}
System.out.println();
//reset token number
tokenNumber = 0;
}
} catch (Exception e) {
System.err.println("CSV file cannot be read : " + e);
}
}
}
this is the file I'm working on :
ImageFormat=GeoTIFF
ProcessingLevel=GEO
ResampCode=CC
NoScans=10496
NoPixels=10944
MapProjection=UTM
Ellipsoid=WGS_84
Datum=WGS_84
MapOriginLat=0.00000000
MapOriginLon=0.00000000
ProdULLat=18.54590200
ProdULLon=73.80059300
ProdURLat=18.54653200
ProdURLon=73.90427600
ProdLRLat=18.45168500
ProdLRLon=73.90487900
ProdLLLat=18.45105900
ProdLLLon=73.80125300
ProdULMapX=373416.66169100
ProdULMapY=2051005.23286800
ProdURMapX=384360.66169100
ProdURMapY=2051005.23286800
ProdLRMapX=373416.66169100
ProdLRMapY=2040509.23286800
ProdLLMapX=384360.66169100
ProdLLMapY=2040509.23286800
Out of this, i need to display only the following :
NoScans
NoPixels
ProdULLat
ProdULLon
ProdLRLat
ProdLRLon
public class Test {
public String getValue(String str, String strDelim, String keyValueDelim, String key){
StringTokenizer tokens = new StringTokenizer(str, strDelim);
String sentence;
while(tokens.hasMoreElements()){
sentence = tokens.nextToken();
if(sentence.contains(key)){
return sentence.split(keyValueDelim)[1];
}
}
return null;
}
public static void main(String[] args) {
System.out.println(new Test().getValue("apple = 23456, mango = 12345, orange= 76548, guava = 56734", ",", "=", "apple"));
}
}
" I noticed you have edited your question and added your code. for your new version question you can still simply call method while reading the String from the file and get your desire value ! "
I have written code assuming you have already stored data from file to a String,
public static void main(String[] args) {
try {
String[] CONSTANTS = {"apple", "guava"};
String input = "apple = 23456, mango = 12345, orange= 76548, guava = 56734";
String[] token = input.split(",");
for(String eachToken : token) {
String[] subToken = eachToken.split("=");
// checking whether this data is required or not.
if(subToken[0].trim().equals(CONSTANTS[0]) || subToken[0].trim().equals(CONSTANTS[1])) {
System.out.println("No Need to do anything");
} else {
System.out.println(subToken[0] + " " + subToken[1]);
}
}
} catch(Exception e) {
e.printStackTrace();
}
}
read a complete line using bufferedreader and pass it to stringtokenizer with tokenizer as "="[as you mentioned in your file].
for more please paste your file and what you have tried so far..
ArrayList<String> list = new ArrayList<String>();
list.add("NoScans");
list.add("NoPixels");
list.add("ProdULLat");
list.add("ProdULLon");
list.add("ProdLRLat");
list.add("ProdLRLon");
//read a line from a file.
while ((line = br.readLine()) != null) {
lineNumber++;
//use 'equal to' as token separator
st = new StringTokenizer(line, "=");
//check for tokens from the above string tokenizer.
while (st.hasMoreTokens()) {
String key = st.nextToken(); //this will give the first token eg: NoScans
String value = st.nextToken(); //this will give the second token eg:10496
//check the value is present in the list or not. If it is present then print
//the value else leave it as it is.
if(list.contains(key){
//display csv values
System.out.print(key+"="+ " "+value);
}
}