I have a class Called File
Location which stores the size, name, drive and directory of a file.
The class is supposed to separate the extension from the file name ("java" from "test.java") then compare it to another file using an equals method. Though for some reason it is returning false everytime. Any idea what's wrong?
Class file
import java.util.*;
public class FileLocation
{
private String name;
private char drive;
private String directory;
private int size;
public FileLocation()
{
drive = 'X';
directory = "OOProgramming\\Practicals\\";
name = "test";
size = 2;
}
public FileLocation(char driveIn, String dirIn, String nameIn, int sizeIn)
{
drive = driveIn;
directory = dirIn;
name = nameIn;
size = sizeIn;
}
public String getFullPath()
{
return drive + ":\\" + directory + name;
}
public String getFileType()
{
StringTokenizer st1 = new StringTokenizer(name, ".");
return "File type is " + st1.nextToken();
}
public String getSizeAsString()
{
StringBuilder data = new StringBuilder();
if(size > 1048575)
{
data.append("gb");
}
else if(size > 1024)
{
data.append("mb");
}
else
{
data.append("kb");
}
return size + " " + data;
}
public boolean isTextFile()
{
StringTokenizer st2 = new StringTokenizer(name, ".");
if(st2.nextToken() == ".txt" || st2.nextToken() == ".doc")
{
return true;
}
else
{
return false;
}
}
public void appendDrive()
{
StringBuilder st1 = new StringBuilder(drive);
StringBuilder st2 = new StringBuilder(directory);
StringBuilder combineSb = st1.append(st2);
}
public int countDirectories()
{
StringTokenizer stDir =new StringTokenizer(directory, "//");
return stDir.countTokens();
}
public String toString()
{
return "Drive: " + drive + " Directory: " + directory + " Name: " + name + " Size: " + size;
}
public boolean equals(FileLocation f)
{
return drive == f.drive && directory == f.directory && name == f.name && size == f.size;
}
}
Tester program
import java.util.*;
public class FileLocationTest
{
public static void main(String [] args)
{
Scanner keyboardIn = new Scanner(System.in);
FileLocation javaAssign = new FileLocation('X', "Programming\\Assignment\\", "Loan.txt", 1);
int selector = 0;
System.out.print(javaAssign.isTextFile());
}
}
this code will give true only if the file is doc.
StringTokenizer st2 = new StringTokenizer(name, ".");
if(st2.nextToken() == ".txt" || st2.nextToken() == ".doc")
if file name file.txt then what happend
(st2.nextToken() == ".txt") means ("file" == "txt") false
(st2.nextToken() == ".doc") means ("txt" == "txt") false
first token will gave file name second token will gave ext.
right code is
StringTokenizer st2 = new StringTokenizer(name, ".");
String filename = st2.nextToken();
String ext = st2.nextToken();
if(ext.equalsIgnoreCase(".txt") || ext.equalsIgnoreCase(".txt"))
use always equals to compare strings not ==
Take a look at my own question I posted a while back. I ended up using Apache Lucene's tokenizer.
Here is how you use it (copied from here):
TokenStream tokenStream = analyzer.tokenStream(fieldName, reader);
OffsetAttribute offsetAttribute = tokenStream.addAttribute(OffsetAttribute.class);
CharTermAttribute charTermAttribute = tokenStream.addAttribute(CharTermAttribute.class);
while (tokenStream.incrementToken()) {
int startOffset = offsetAttribute.startOffset();
int endOffset = offsetAttribute.endOffset();
String term = charTermAttribute.toString();
}
Related
I have a file that contains more than one value in one column. I was trying to read this file using java with this code:
ArrayList<String> linesList1 = new ArrayList<>();
ArrayList<String> roadlinkid = new ArrayList<>();
ArrayList<String> road_name_orignal = new ArrayList<>();
ArrayList<String> road_name_copy = new ArrayList<>();
ArrayList<String[]> networkmember_href = new ArrayList<>();
ArrayList<String> road_fid = new ArrayList<>();
// Input of file which needs to be parsed
String csvFile1 = "RoadData.csv";
BufferedReader csvReader1;
// Data split by ',' in CSV file
String csvSplitBy = ",";
try {
String line;
csvReader1 = new BufferedReader(new FileReader(csvFile1));
while ((line = csvReader1.readLine()) !=null) {
linesList1.add(line);
}
csvReader1.close();
}
catch (IOException e) { e.printStackTrace(); }
for (int i = 0; i < linesList1.size(); i++) {
String[] data = linesList1.get(i).split(csvSplitBy);
road_fid.add( data[1]);
road_name_orignal.add( data[9]);
if (data[9].contains("{")) {
String[] xy = data[9].replaceAll("\\{|\\}", "").split(",");
int leng = xy.length;
String[] networkmember = new String [leng];
for ( int n = 0 ; n < leng ; n++) {
networkmember[n] = xy [n];
}
networkmember_href.add(networkmember);
}
}
This code works well, but the problem is that the code deals with each value in the column as a separate column. Therefore, it returns wrong data.
Files:
http://s000.tinyupload.com/?file_id=47090134488569683648
The idea is Finding the road name from RoadData.csv and write it in RoadLink.csv by comparing road_fid in RoadData.csv and roadlink_fid in RoadLink.csv. Unfortunately, I could find a way to deal with a column with multi-values. Any advice, please.
Thanks in advance.
Below is some code to parse the file, you can add additional processing to parse the fields that have lists in them or to combine the lists like changedate and reasonforchange into a list of Objects containing both pieces of data. For example a List<ChangeInfo> where ChangeInfo holds both the changedate and reasonforchange.
I still would recommend using a csv parser but this code should work well enough for this specific use case. Test thoroughly..
Main:
public static void main(String[] args){
List<RoadLinkRecord> records = parse("path\\to\\RoadLink.csv");
// display all the records
for (RoadLinkRecord record : records) {
System.out.println(record);
}
}
CSV Parsing:
private static final Pattern csvFieldPattern =
Pattern.compile("(?<=[$,])(\"(\"\"|[^\"])*\"|[^,]*)");
/** This parse method requires the CSV file to have a header row */
public static List<RoadLinkRecord> parse(String csvFilePath) {
// TODO accept Reader or maybe InputStream rather than file path
File f = new File(csvFilePath);
List<RoadLinkRecord> records = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader(f));) {
// get the header fields
String line = br.readLine();
List<String> headers = new ArrayList<>();
{
Matcher matcher = csvFieldPattern.matcher(line);
while (matcher.find())
headers.add(matcher.group());
}
// iterate through record fields
int recordNum = 0;
while ((line = br.readLine()) != null) {
recordNum++;
// allocate array to hold the fields
String[] fields = new String[headers.size()];
// use matcher to get each of the fields
Matcher matcher = csvFieldPattern.matcher(line);
for (int i = 0; i < headers.size(); i++) {
if (!matcher.find()) {
throw new IllegalArgumentException(
"Couldn't find field '" + headers.get(i) + "' for record " + recordNum);
}
fields[i] = matcher.group();
}
if (matcher.find()) {
throw new IllegalArgumentException("Found excess fields in record " + recordNum);
}
// add the record from this line
records.add(new RoadLinkRecord(recordNum, fields));
}
} catch (IOException e) {
// TODO trouble reading the file
} catch (IllegalArgumentException e) {
// TODO error while parsing the file
}
return records;
}
Data Container:
public class RoadLinkRecord {
private final int recordNumber;
private final String roadlink_fid;
private final String version;
private final String versiondate;
private final String changedate;
private final String reasonforchange;
private final String descriptivegroup;
private final String descriptiveterm;
private final String natureofroad;
private final String length;
private final String directednode_href;
private final String directednode_orientation;
private final String directednode_gradeseparation;
private final String referencetotopographicarea_href;
private final String theme;
private final String filename;
private final String wkb_geometry;
private final String roadnumber;
private final String dftname;
private final String fid;
private final String roadname;
public RoadLinkRecord(final int recordNumber, final String[] csvFields) {
if (csvFields.length != 20) {
throw new IllegalArgumentException(
"Wrong number of fields for a RoadLinkRecord! Expected 20, found "
+ csvFields.length);
}
this.recordNumber = recordNumber;
this.roadlink_fid = processStringField(csvFields[0]);
this.version = processStringField(csvFields[1]);
this.versiondate = processStringField(csvFields[2]);
this.changedate = processStringField(csvFields[3]);
this.reasonforchange = processStringField(csvFields[4]);
this.descriptivegroup = processStringField(csvFields[5]);
this.descriptiveterm = processStringField(csvFields[6]);
this.natureofroad = processStringField(csvFields[7]);
this.length = processStringField(csvFields[8]);
this.directednode_href = processStringField(csvFields[9]);
this.directednode_orientation = processStringField(csvFields[10]);
this.directednode_gradeseparation = processStringField(csvFields[11]);
this.referencetotopographicarea_href = processStringField(csvFields[12]);
this.theme = processStringField(csvFields[13]);
this.filename = processStringField(csvFields[14]);
this.wkb_geometry = processStringField(csvFields[15]);
this.roadnumber = processStringField(csvFields[16]);
this.dftname = processStringField(csvFields[17]);
this.fid = processStringField(csvFields[18]);
this.roadname = processStringField(csvFields[19]);
}
private static String processStringField(String field) {
// consider empty fields as null
if (field.isEmpty()) {
return null;
}
// strip double quotes and replace any escaped quotes
final int endIndex = field.length() - 1;
if (field.charAt(0) == '"' && field.charAt(endIndex) == '"') {
return field.substring(1, endIndex).replace("\"\"", "\"");
}
return field;
}
public int getRecordNumber() { return recordNumber; }
public String getRoadlink_fid() { return roadlink_fid; }
public String getVersion() { return version; }
public String getVersiondate() { return versiondate; }
public String getChangedate() { return changedate; }
public String getReasonforchange() { return reasonforchange; }
public String getDescriptivegroup() { return descriptivegroup; }
public String getDescriptiveterm() { return descriptiveterm; }
public String getNatureofroad() { return natureofroad; }
public String getLength() { return length; }
public String getDirectednode_href() { return directednode_href; }
public String getDirectednode_orientation() { return directednode_orientation; }
public String getDirectednode_gradeseparation() { return directednode_gradeseparation; }
public String getReferencetotopographicarea_href() { return referencetotopographicarea_href; }
public String getTheme() { return theme; }
public String getFilename() { return filename; }
public String getWkb_geometry() { return wkb_geometry; }
public String getRoadnumber() { return roadnumber; }
public String getDftname() { return dftname; }
public String getFid() { return fid; }
public String getRoadname() { return roadname; }
#Override
public String toString() {
return "roadlink_fid= " + roadlink_fid + "; version= " + version + "; versiondate= "
+ versiondate + "; changedate= " + changedate + "; reasonforchange= "
+ reasonforchange + "; descriptivegroup= " + descriptivegroup + "; descriptiveterm= "
+ descriptiveterm + "; natureofroad= " + natureofroad + "; length= " + length
+ "; directednode_href= " + directednode_href + "; directednode_orientation= "
+ directednode_orientation + "; directednode_gradeseparation= "
+ directednode_gradeseparation + "; referencetotopographicarea_href= "
+ referencetotopographicarea_href + "; theme= " + theme + "; filename= " + filename
+ "; wkb_geometry= " + wkb_geometry + "; roadnumber= " + roadnumber + "; dftname= "
+ dftname + "; fid= " + fid + "; roadname= " + roadname + ";";
}
}
I try to remove a space into a string which contains a int type value.
I read a .csv file with the scanner methode.
I use a Class to set/get the data.
I format data into the setter of the class.
Input data example:
String Pu_ht = "1 635,90";
Basic Example:
/**
* #param Pu_ht the Pu_ht to set
*/
public void setPu_ht(String Pu_ht) {
this.Pu_ht = Pu_ht.replace(",", ".").replace(".00", "");
}
Tried example:
/**
* #param Pu_ht the Pu_ht to set
*/
public void setPu_ht(String Pu_ht) {
this.Pu_ht = Pu_ht.replace(",", ".").replace(".00", "").replaceAll("\\s+", "");
}
Other example:
/**
* #param Pu_ht the Pu_ht to set
*/
public void setPu_ht(String Pu_ht) {
this.Pu_ht = Pu_ht.replace(",", ".").replace(".00", "").replaceAll(" ", "");
}
Output data example: 1 635.90
I tried a lots of things but nothing work for my case.
Best regards
EDIT:
My code:
public void requete_pommes() throws IOException, ClassNotFoundException, SQLException {
// open file input stream
BufferedReader reader = new BufferedReader(new FileReader(filename));
// read file line by line
String line = null;
Scanner scanner = null;
int index = 0;
List<Pommes> pomList = new ArrayList<>();
boolean firstLine = false;
while ((line = reader.readLine()) != null) {
if (!(line.equals(";;;;TOTAL HT"))) {
if (!(line.equals(";;;;"))) {
Pommes pom = new Pommes();
scanner = new Scanner(line);
scanner.useDelimiter(";");
while (scanner.hasNext()) {
String data = scanner.next();
pom.setNumero_compte("21826");
if ((index == 0)) {
pom.setReference(data);
} else if ((index == 1)) {
pom.setDesignation(data);
} else if ((index == 2)) {
pom.setQte(data);
} else if ((index == 3)) {
if(data.equals("1 635,90")){
data = data.replaceAll("\\s","");
System.err.println("data: " + data);
}
pom.setPu_ht(data);
} else if ((index == 4)) {
pom.setMontant_HT(data);
} else {
System.out.println("invalid data::" + data);
}
pom.setNumero_commande("1554");
index++;
}
index = 0;
pomList.add(pom);
requeteCorps = "(( SELECT codea FROM article WHERE tarif7 != 'O' AND tarif8 = 'O' AND pvente > 0 AND COALESCE(trim( reffou), '') != '' AND reffou = '" + pom.getReference() + "' ), " + pom.getQte() + " , " + pom.getPu_ht() + ", '" + kapiece + "', 'stomag','vendu', getnum('LCK')),";
ar.add(requeteCorps);
}
}
}
The value "1 635,90" probably stems from a locale specific format, and the "space" actually is a non-breaking space, \u00A0. This is done often to prevent in flexible width text representation a line break to happen inside a number.
s = s.replace("\u00A0", "");
String Pu_ht = "1 635,90";
System.out.println(Pu_ht.replace(",", ".").replace(".00", "").replaceAll("\\s+", ""));
just put the above codes in main method and execute. the output will be 1635.90,then examine your codes.
I have a method to read a text file of five stocks using Scanner and delimiter. I also have a method which should take a double multiplier and an array of stock objects and change the price with that multiplier. The method which reads the stock file functions correctly, however, when I attempt to change the stock objects that have been assigned values with the filereading method, it does not change the price. After I use method updateStocks(), I test stock[1] to see if the value has changed and it has not.
After I run this:
public class Main {
public static void main (String args[]) {
// stock object with which to call methods
Stock theStock = new Stock("", "", 0);
// this array holds the stocks to be read
Stock[] stocks = new Stock[100];
// here is the multiplier I am attempting to use
double multiplier = 1/3;
// first I read in the stocks file
theStock.readStocksWithScanner(stocks);
// then I call the updateStockPrices method
theStock.updateStockPrices(multiplier,stocks);
// lastly, I test to see if the method has functioned correctly
System.out.println(stocks[1]);
}
}
This is my output:
Apple AAPLE 152.70
Alphabet GOOGLE 873.96
IBM IBM 194.37
Microsoft MSFT 65.67
Oracle ORCLE 62.82
Company name: Apple Stock symbol: AAPLE Stock Price: 152.7
Press any key to continue . . .
Here is the method updateStockPrices:
// this is the method which does not seem to function as intended
public void updateStockPrices(double multiplier, Stock[] objects)
{
// I loop to the length of the array in the parameter
for(int i = 1; i < objects.length; i++)
{
// try to manipulate the stock
try{
double subtractThis = stocks[i].getPrice() * multiplier;
objects[i].setPrice(stocks[i].getPrice() - subtractThis);
}// and catch any null objects
catch(NullPointerException e){
// if null I then increment the counter
i++;}
// Is code missing in order for this to function as intended? or have I made a mistake?
}
}
and here is stocks.java:
import java.util.Scanner ;
import java.util.InputMismatchException ;
import java.io.FileInputStream ;
import java.io.IOException ;
import java.io.FileNotFoundException ;
import java.io.PrintWriter ;
public class Stock {
private static final double MULTIPLIER = (1/3);
public static final String FILE_NAME = "stocks1.txt";
public String newFile = "stocks2.txt";
public static final String FORMAT = "%-10s%6s\t%.2f%n";
private PrintWriter writer = null;
private String name = "";
private String symbol = "";
private double price = 0;
protected Stock stocks[] = new Stock[100];
FileInputStream inputStream = null;
String workingDirectory = System.getProperty("user.dir");
String absolutePath = workingDirectory + "\\" + FILE_NAME;
public Stock(String aName, String aSymbol, double aPrice)
{
this.name = aName;
this.symbol = aSymbol;
this.price = aPrice;
}
// the fileReading method reads the stocks in
public void readStocksWithScanner(Stock[] stocks)
{
this.stocks = stocks;
String workingDirectory = System.getProperty("user.dir");
String absolutePath = workingDirectory + "\\" + FILE_NAME;
FileInputStream inputStream = null;
try{
inputStream = new FileInputStream(absolutePath);
}
catch (FileNotFoundException e)
{
System.out.println("File not found: " + FILE_NAME);
System.out.println("Exiting program.");
System.exit(0) ;
}
Scanner inputFile = new Scanner(inputStream);
int lineNumber = 1;
try{
while(inputFile.hasNextLine())
{
inputFile.useDelimiter(",");
String name = inputFile.next();
inputFile.useDelimiter(",");
String symbol = inputFile.next();
inputFile.useDelimiter("[,\\s]") ;
Double thePrice = inputFile.nextDouble();
inputFile.nextLine();
// here the stocks are given the values found in the text file and initialized above
stocks[lineNumber] = new Stock(name, symbol, thePrice);
// I print them out using a format constant, in order to ensure the method has functioned correcly
System.out.printf(FORMAT, name, symbol, thePrice);
// then I increment the lineNumber
lineNumber++;
}
// I close the stream and should be left with a partially filled array of stock items
inputStream.close();
}catch (IOException e) {
System.out.println("Error reading line " + lineNumber + " from file " + FILE_NAME) ;
System.exit(0) ;
}
catch(InputMismatchException e) {
System.out.println("Couldn't convert price to a number on line " + lineNumber) ;
System.exit(0) ;}
}
public void setName(String name)
{
this.name = name;
}
public void setSymbol(String symbol)
{
this.symbol = symbol;
}
public void setPrice(double aPrice)
{
this.price = aPrice;
}
public String getName()
{
return name;
}
public String getSymbol()
{
return symbol;
}
public double getPrice()
{
return price;
}
public boolean equals(Object other)
{
if(other.getClass() != getClass() || other == null )
{
return false;
}
Stock stock = (Stock) other;
{
if(stock.getName() == getName() && stock.getSymbol() == getSymbol() && stock.getPrice() == getPrice())
{
return true;
}
return false;
}
}
public String toString()
{
return "Company name: " + getName() + " Stock symbol: " + getSymbol() + " Stock Price: " + getPrice();
}
// this is the method which does not seem to function as intended
public void updateStockPrices(double multiplier, Stock[] objects)
{
// I loop to the length of the array in the parameter
for(int i = 1; i < objects.length; i++)
{
// try to manipulate the stock
try{
double subtractThis = stocks[i].getPrice() * multiplier;
objects[i].setPrice(stocks[i].getPrice() - subtractThis);
}// and catch any null objects
catch(NullPointerException e){
// if null I then increment the counter
i++;}
// Is code missing in order for this to function as intended? or have I made a mistake?
}
}
public void createStocks(int stockAmount)
{
Stock[] stocks = new Stock[stockAmount];
}
public void writeStocks(String fileName, Stock[] objects)
{
try{
writer = new PrintWriter(fileName);
}
catch(FileNotFoundException e){
System.out.println("Couldn't create file " + fileName);
System.exit(0);
}
for(Stock s: objects)
{
writer.printf(FORMAT, getName(), getSymbol(), getPrice());
if(objects == null)
writer.close() ;
}
}
public Stock[] getStocks()
{
return stocks;
}
}
simple test
double multiplier = 1/3;
System.out.println(multiplier);
compared to
double multiplier = 1/3f;
System.out.println(multiplier);
I'm doing a Phone Directory project and we have to read from a directory file telnos.txt
I'm using a Scanner to load the data from the file telnos.txt, using a loadData method from a previous question I asked here on StackOverflow.
I noticed attempts to find a user always returned Not Found, so I added a few System.out.printlns in the methods to help me see what was going on. It looks like the scanner isn't reading anything from the file. Weirdly, it is printing the name of the file as what should be the first line read, which makes me think I've missed something very very simple here.
Console
run:
telnos.txt
null
loadData tested successfully
Please enter a name to look up: John
-1
Not found
BUILD SUCCESSFUL (total time: 6 seconds)
ArrayPhoneDirectory.java
import java.util.*;
import java.io.*;
public class ArrayPhoneDirectory implements PhoneDirectory {
private static final int INIT_CAPACITY = 100;
private int capacity = INIT_CAPACITY;
// holds telno of directory entries
private int size = 0;
// Array to contain directory entries
private DirectoryEntry[] theDirectory = new DirectoryEntry[capacity];
// Holds name of data file
private final String sourceName = "telnos.txt";
File telnos = new File(sourceName);
// Flag to indicate whether directory was modified since it was last loaded or saved
private boolean modified = false;
// add method stubs as specified in interface to compile
public void loadData(String sourceName) {
Scanner read = new Scanner("telnos.txt").useDelimiter("\\Z");
int i = 1;
String name = null;
String telno = null;
while (read.hasNextLine()) {
if (i % 2 != 0)
name = read.nextLine();
else
telno = read.nextLine();
add(name, telno);
i++;
}
}
public String lookUpEntry(String name) {
int i = find(name);
String a = null;
if (i >= 0) {
a = name + (" is at position " + i + " in the directory");
} else {
a = ("Not found");
}
return a;
}
public String addChangeEntry(String name, String telno) {
for (DirectoryEntry i : theDirectory) {
if (i.getName().equals(name)) {
i.setNumber(telno);
} else {
add(name, telno);
}
}
return null;
}
public String removeEntry(String name) {
for (DirectoryEntry i : theDirectory) {
if (i.getName().equals(name)) {
i.setName(null);
i.setNumber(null);
}
}
return null;
}
public void save() {
PrintWriter writer = null;
// writer = new PrintWriter(FileWriter(sourceName));
}
public String format() {
String a;
a = null;
for (DirectoryEntry i : theDirectory) {
String b;
b = i.getName() + "/n";
String c;
c = i.getNumber() + "/n";
a = a + b + c;
}
return a;
}
// add private methods
// Adds a new entry with the given name and telno to the array of
// directory entries
private void add(String name, String telno) {
System.out.println(name);
System.out.println(telno);
theDirectory[size] = new DirectoryEntry(name, telno);
size = size + 1;
}
// Searches the array of directory entries for a specific name
private int find(String name) {
int result = -1;
for (int count = 0; count < size; count++) {
if (theDirectory[count].getName().equals(name)) {
result = count;
}
System.out.println(result);
}
return result;
}
// Creates a new array of directory entries with twice the capacity
// of the previous one
private void reallocate() {
capacity = capacity * 2;
DirectoryEntry[] newDirectory = new DirectoryEntry[capacity];
System.arraycopy(theDirectory, 0, newDirectory,
0, theDirectory.length);
theDirectory = newDirectory;
}
}
ArrayPhoneDirectoryTester.java
import java.util.Scanner;
public class ArrayPhoneDirectoryTester {
public static void main(String[] args) {
//create a new ArrayPhoneDirectory
PhoneDirectory newTest = new ArrayPhoneDirectory();
newTest.loadData("telnos.txt");
System.out.println("loadData tested successfully");
System.out.print("Please enter a name to look up: ");
Scanner in = new Scanner(System.in);
String name = in.next();
String entryNo = newTest.lookUpEntry(name);
System.out.println(entryNo);
}
}
telnos.txt
John
123
Bill
23
Hello
23455
Frank
12345
Dkddd
31231
In your code:
Scanner read = new Scanner("telnos.txt");
Is not going to load file 'telnos.txt'. It is instead going to create a Scanner object that scans the String "telnos.txt".
To make the Scanner understand that it has to scan a file you have to either:
Scanner read = new Scanner(new File("telnos.txt"));
or create a File object and pass its path to the Scanner constructor.
In case you are getting "File not found" errors you need to check the current working directory. You could run the following lines and see if you are indeed in the right directory in which the file is:
String workingDir = System.getProperty("user.dir");
System.out.println("Current working directory : " + workingDir);
You need to also catch the FileNotFoundException in the function as follows:
public void loadData(String sourceName) {
try {
Scanner read = new Scanner(new File("telnos.txt")).useDelimiter("\\Z");
int i = 1;
String name = null;
String telno = null;
while (read.hasNextLine()) {
if (i % 2 != 0)
name = read.nextLine();
else {
telno = read.nextLine();
add(name, telno);
}
i++;
}
}catch(FileNotFoundException ex) {
System.out.println("File not found:"+ex.getMessage);
}
}
You are actually parsing the filename not the actual file contents.
Instead of:
new Scanner("telnos.txt")
you need
new Scanner( new File( "telnos.txt" ) )
http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
I wrote a little test program but I'm experiencing a syntax error in my closing tags...
Here's the code
public class Test
{
AudioFile file = null;
String vbb = "";
File f;
public Test()
{
openFile();
}
public File openFile()
{
JFileChooser fc = new JFileChooser();
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int result = fc.showOpenDialog(fc);
if(result == JFileChooser.CANCEL_OPTION)
{
return null;
} else {
f = fc.getCurrentDirectory();
return f;
}
}
f = new File(openFile());
File[] files = f.listFiles();
for(File fi : files)
{
try {
file = (AudioFile) AudioFileIO.read(new File(fi.getAbsolutePath()));
MP3AudioHeader ah = (MP3AudioHeader) file.getAudioHeader();
String time = ah.getTrackLengthAsString();
String rate = ah.getBitRate();
boolean vb = ah.isVariableBitRate();
if(vb == false)
{
vbb = "Nee";
} else {
vbb = "Ja";
}
Tag tag = file.getTag();
String artist = tag.getFirst(FieldKey.ARTIST);
String title = tag.getFirst(FieldKey.TITLE);
String album = tag.getFirst(FieldKey.ALBUM);
String genre = tag.getFirst(FieldKey.GENRE);
String temo = tag.getFirst(FieldKey.BPM);
String path = fi.getAbsolutePath();
System.out.println("Duur: " + time + "\nVariabele bitrate: " + vbb + "\nArtiest: " + artist +"\nTitel: " + title
+ "\nAlbum: " + album + "\nGenre: " + genre + "\nBPM: " + temo + "\nBitrate: " + rate + " kbps\nPad: " + path);
} catch (Exception e)
{
System.err.print("FOUT");
}
}
}
The compiler gives an error at the LATEST closing accolade:
"Please insert } to complete classbody"
And also at the last accolade of the "openFile()" method...
Any suggestions?
f = new File(openFile());
File[] files = f.listFiles();
for(File fi : files)
{
//...
}
This whole block of logic is not in a method. It needs to be in a method or constructor.
Where you have
f = new File ...
...
catch ( .. )
{
....
}
You want to wrap that in
public static void main (String args[]) {
....
}
You cannot have a code block in a class definition. At the very top of the class, those variable declarations are declarations of class members with default visibility.
All the code starting with the line
f = new File(openFile());
is outside of any method. This is not legal Java: statements must be enclosed in a block or method body.
everything below
public File openFile()
{
JFileChooser fc = new JFileChooser();
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int result = fc.showOpenDialog(fc);
if(result == JFileChooser.CANCEL_OPTION)
{
return null;
} else {
f = fc.getCurrentDirectory();
return f;
}
}
is not enclosed within a method body but is rather lurking in the class body. remove the outer closing brace above.
Your code is not in a method. It needs to be in a method or a static block. Guessing your intent you can put it in the constructor like :
public class Test
{
AudioFile file = null;
String vbb = "";
File f;
public Test()
{
openFile();
f = new File(openFile());
File[] files = f.listFiles();
for(File fi : files)
{
try {
file = (AudioFile) AudioFileIO.read(new File(fi.getAbsolutePath()));
MP3AudioHeader ah = (MP3AudioHeader) file.getAudioHeader();
String time = ah.getTrackLengthAsString();
String rate = ah.getBitRate();
boolean vb = ah.isVariableBitRate();
if(vb == false)
{
vbb = "Nee";
} else {
vbb = "Ja";
}
Tag tag = file.getTag();
String artist = tag.getFirst(FieldKey.ARTIST);
String title = tag.getFirst(FieldKey.TITLE);
String album = tag.getFirst(FieldKey.ALBUM);
String genre = tag.getFirst(FieldKey.GENRE);
String temo = tag.getFirst(FieldKey.BPM);
String path = fi.getAbsolutePath();
System.out.println("Duur: " + time + "\nVariabele bitrate: " + vbb + "\nArtiest: " + artist +"\nTitel: " + title
+ "\nAlbum: " + album + "\nGenre: " + genre + "\nBPM: " + temo + "\nBitrate: " + rate + " kbps\nPad: " + path);
} catch (Exception e)
{
System.err.print("FOUT");
}
}
}
public File openFile()
{
JFileChooser fc = new JFileChooser();
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int result = fc.showOpenDialog(fc);
if(result == JFileChooser.CANCEL_OPTION)
{
return null;
} else {
f = fc.getCurrentDirectory();
return f;
}
}
}