This is the text file I want to read and display on console. Here are my codes for reading the file:
public class CarMain
{
public static void main (String args[]) throws IOException
{
try
{
File f = new File("Cars.txt");
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
String line = "", fullName;
String[] arrName = null;
Car[] c = new Car[3];
String name, ic, manufacturer, model;
int num = 0;
while ((line = br.readLine()) != null)
{
StringTokenizer st = new StringTokenizer(line);
name = st.nextToken();
StringTokenizer st2 = new StringTokenizer(line,"://;");
ic = st2.nextToken();
manufacturer = st2.nextToken();
model = st2.nextToken();
c[num] = new Car(name,ic, manufacturer, model);
num++;
}
br.close();
fr.close();
for (int i = 0; i < c.length; i++)
{
System.out.println(c[i].toString());
}
}
catch(IOException e)
{
JOptionPane.showMessageDialog(null,"error opening file");
}
}
}
then I get this output:
It seems that it doesn't display the model name after ";" and the data is not in the right place.
My expected output is like this:
Name: Fatimah Zahra Ali
IC: 860802105012
Manufacturer: Proton
Model: Perdana
.
.
.
Please help. Thank you.
Your st2 is a new tokenizer. You should read the tokens from st2 as follows:
StringTokenizer st2 = new StringTokenizer(line,"://;");
name = st2.nextToken(); // first token
ic = st2.nextToken(); // second
manufacturer = st2.nextToken(); // third
model = st2.nextToken(); // fourth
The first tokenizer is not required.
I have put all st2 but the name is missing.
Related
I would like to randomly select single name from column1 between Robert,Shawn,John.
Example The File has following names
Robert,Brian
Shawn,Bay
John,Paul
Any Help would be highly appreciated
FileInputStream objfile = new FileInputStream(System.getProperty("user.dir")+path);
in = new BufferedReader(new InputStreamReader(objfile ));
String line = in.readLine();
while (line != null && !line.trim().isEmpty()) {
String eachRecord[]=line.trim().split(",");
Random rand = new Random();
//trying to randomly select text from specific row in a property file
sendKeys(firstName,rand.nextInt((eachRecord[0]));
line = in.readLine();
}
}
This gets a random name from column 1 into the variable randomName:
final int column = 1;
final String path = "file.ext";
Random rand = new Random();
List<String> lines = Files.readAllLines(Paths.get(path), StandardCharsets.UTF_8);
String randomName = lines.get(rand.nextInt(lines.size())).split(",")[column - 1];
FileReader fr = new FileReader(path_of_your_file);
BufferedReader br = new BufferedReader(fr);
String sCurrentLine;
ArrayList<String> nameList=new ArrayList<String>(); //keep each first column entry inside this list.
while ((sCurrentLine = br.readLine()) != null) {
StringTokenizer st=new StringTokenizer(sCurrentLine, ",");
String name=st.nextToken();
nameList.add(name);
}
System.out.println(nameList.get((int)(Math.random()*nameList.size())));
//close file resources at finally block.
I have a text file which has text as follows:
emVersion = "1.32.4.0";
ecdbVersion = "1.8.9.6";
ReleaseVersion = "2.3.2.0";
I want to update the version number by taking the input from a user if user enter the new value for emVersion as 1.32.5.0 then
emVersion in text file will be updated as emVersion = "1.32.5.0";
All this I have to do using java code. What I have done till now is reading text file line by line then in that searching the word emVersion if found the broken line into words and then replace the token 1.32.4.0 but it is not working because spaces are unequal in the file.
Code what i have written is :
public class UpdateVariable {
public static void main(String s[]){
String replace = "1.5.6";
String UIreplace = "\""+replace+"\"";
File file =new File("C:\\Users\\310256803\\Downloads\\setup.rul");
Scanner in = null;
try {
in = new Scanner(file);
while(in.hasNext())
{
String line=in.nextLine();
if(line.contains("svEPDBVersion"))
{
String [] tokens = line.split("\\s+");
String var_1 = tokens[0];
String var_2 = tokens[1];
String var_3 = tokens[2];
String var_4 = tokens[3];
String OldVersion = var_3;
String NewVersion = UIreplace;
try{
String content = IOUtils.toString(new FileInputStream(file), StandardCharsets.UTF_8);
content = content.replaceAll(OldVersion, NewVersion);
IOUtils.write(content, new FileOutputStream(file), StandardCharsets.UTF_8);
} catch (IOException e) {
}
}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//---this code changes each version's values but the is a option to keep the old value.
Scanner in = new Scanner(System.in);
File file = new File("versions.txt");
ArrayList<String> data = new ArrayList<>();
String[] arr =
{
"emVersion", "ecdbVersion", "releaseVersion"
};
String line = "";
String userInput = "";
try (BufferedReader br = new BufferedReader(new FileReader(file));)
{
while ((line = br.readLine()) != null)
{
data.add(line);
}
for (int i = 0; i < arr.length; i++)
{
System.out.println("Please enter new " + arr[i] + " number or (s) to keep the old value.");
userInput = in.nextLine();
line = data.get(i);
String version = line.substring(0, line.indexOf(" "));
if (arr[i].equalsIgnoreCase(version))
{
arr[i] = line.replace(line.subSequence(line.indexOf("= "), line.indexOf(";")), "= \"" + userInput + "\"");
}
if (userInput.equalsIgnoreCase("s"))
{
arr[i] = line;
}
}
PrintWriter printWriter = new PrintWriter(new FileWriter(file, false));
printWriter.println(arr[0]);
printWriter.println(arr[1]);
printWriter.println(arr[2]);
printWriter.close();
}
catch (Exception e)
{
System.out.println("Exception: " + e.getMessage());
}
Use regular expression eg:- line.trim().split("\s*=\s*"); . If it does not work please let me know , i will provide you complete solution.
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);
}
}
I want to write small java program to read data file first field and add seqcution number
Input file:
robert,190 vikign,...
robert,2401 windy,...
robert,1555 oakbrook,...
michell,2524 sprint,...
michell,1245 oakbrrok,...
xyz,2455 xyz drive,....
Output file should be:
robert,190 vikign,...,0
robert,2401 windy,...,1
robert,1555 oakbrook,...,2
michell,2524 sprint,...,0
michell,1245 oakbrrok,...,1
xyz,2455 xyz drive,....,0
Check first field when value change sequction number start back to 0 otherwise add sequction number by 1
here is my code:
public static void createseq(String str) {
try {
BufferedReader br = null;
BufferedWriter bfAllBWP = null;
File folderall = new File("Sort_Data_File_Out");
File[] BFFileall = folderall.listFiles();
for (File file : BFFileall) {
br = new BufferedReader(new FileReader(file));
String bwp = "FinalDataFileOut\\" + str;
bfAllBWP = new BufferedWriter(new FileWriter(bwp));
String line;
line = br.readLine();
String[] actionID = line.split("\\|");
String fullname = actionID[0].trim();
int seq = 0;
String fullnameb;
while ((line = br.readLine()) != null) {
actionID = line.split("\\|");
fullnameb = actionID[0].trim();
if(fullname.equals(fullnameb)) {
seq++;
}
else {
System.out.println(line + "======" + seq + "\n");
seq = 0;
fullname = fullnameb;
}
System.out.println("dshgfsdj "+line + "======" + seq + "\n");
}
}
}
catch(Exception letterproof) {
letterproof.printStackTrace();
}
}
The below code will fix the issue.I have updated the code if you face any pblm plz let me know :
Input :
robert,190 vikign,...
robert,2401 windy,...
robert,1555 oakbrook,...
michell,2524 sprint,...
michell,1245 oakbrrok,...
xyz,2455 xyz drive,....
Code :
public static void createseq() {
try {
File file = new File("d:\\words.txt"); //Hardcoded file for testing locally
BufferedReader br = new BufferedReader(new FileReader(file));
HashMap<String,Integer> counter = new HashMap<String, Integer>();
String line;
while((line = br.readLine())!= null)
{
String[] actionID = line.split(",");
String firstName = actionID[0];
if(counter.containsKey(firstName))
{
counter.put(firstName, counter.get(firstName) + 1);
}
else
{
counter.put(firstName,0);
}
System.out.println(line+" "+counter.get(firstName));
}
br.close();
} catch(Exception letterproof) {
letterproof.printStackTrace();
}
}
Ouput Come :
robert,190 vikign,... 0
robert,2401 windy,... 1
robert,1555 oakbrook,... 2
michell,2524 sprint,... 0
michell,1245 oakbrrok,... 1
xyz,2455 xyz drive,.... 0
i am working on netbeans...i need to read a file and tokenize then and store it in an array for my future operations....i have attached the code where the line5 contains the tokens...while converting into array iam getting error as
Exception :
" Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 1000
at preprocess.mainpage.jButton2ActionPerformed(mainpage.java:224)
at preprocess.mainpage.access$100(mainpage.java:18)
at preprocess.mainpage$2.actionPerformed(mainpage.java:62)"
Code:
int counter=-1;
int n=0;
String[] arr = new String[1000];
try
{
BufferedReader b = new BufferedReader(new FileReader("C:/Users/sky/Documents/NetBeansProjects/Preprocess/src/preprocess/cdr1.txt"));
String line;
while ((line = b.readLine()) != null)
{
counter+=1;
StringTokenizer st2 = new StringTokenizer(line, " ");
String line5 = (String) st2.nextElement();
arr[n] = line5;
n++;
}
}
catch (Exception e)
{
}
ArrayIndexOutOfBoundsException because may be your array size is less. So better use ArrayList like following:
int counter=-1;
int n=0;
//String[] arr = new String[1000];
List<String> list = new ArrayList<String>(); // Create ArrayList
try{
BufferedReader b = new BufferedReader(new FileReader("C:/Users/sky/Documents/NetBeansProjects/Preprocess/src/preprocess/cdr1.txt"));
String line;
while ((line = b.readLine()) != null) {
counter+=1;
StringTokenizer st2 = new StringTokenizer(line, " ");
String line5 = (String) st2.nextElement();
//arr[n] = line5;
//n++;
list.add(line5); // Add you string into list
}
String[] aa = list.toArray(new String[0]); // convert list into String of array if you need it
}
catch (Exception e){
}