I'm reading from a file that has the following format:
name : symptoms : causes : treatments : rate : prognosis
There are a total of 21 entries but when I try to read from the file and use .split(":");, the output changes each time but is always along the lines of: [Ljava.lang.String;#614951ff. I'm guessing it's the pointer or memory address but I want the String value. I'm not getting any exceptions though so I'm not sure where I've gone wrong. The purpose of the method is to read the file and split into an array using the delimiter for the given file row selected.
public String[] readCancer(int row) {
cancers = new String[22];
FileInputStream fis;
InputStreamReader isr;
BufferedReader br = null;
String eachCancer;
String[] splitCancer = null;
int j = 0;
try {
fis = new FileInputStream(myData);
isr = new InputStreamReader(fis);
br = new BufferedReader(isr);
input = new Scanner(br);
while(input.hasNext() && j < 23) {
cancers[j++] = input.nextLine();
}
eachCancer = cancers[row].toString();
splitCancer = eachCancer.split(":");
} catch (IOException iox) {
JOptionPane.showMessageDialog(null, "Problem with file input");
} finally {
try {
if(br != null) {
br.close();
}
} catch (IOException iox) {
JOptionPane.showMessageDialog(null, "Problem closing the file");
}
}
return splitCancer;
}
To print the contents of array :
1) System.out.println(Arrays.deepToString(splitCancer));
2) System.out.println(Arrays.toString(splitCancer));
3) System.out.println(Arrays.asList(splitCancer));
If you want to display the string array, you should use:
System.out.println(Arrays.toString(splitCancer));
Because when you print splitCancer you'll get the address of the array and not the content of it.
Of course you can print the content in other ways:
for(String str : splitCancer) {
System.out.println(str);
}
Currently I have the following:
public String[] readCancer() {
cancers = new String[22];
split = new String[22];
FileInputStream fis;
InputStreamReader isr;
BufferedReader br = null;
String eachCancer;
int j = 0;
try {
fis = new FileInputStream(myData);
isr = new InputStreamReader(fis);
br = new BufferedReader(isr);
input = new Scanner(br);
while(input.hasNext() && j < 23) {
cancers[j] = input.nextLine().toString();
//cancers[j] = input.nextLine();
split[j] = cancers[j].split(":");
//split[j] = "blah"; this line works
j++;
}
System.out.println(Arrays.toString(split));
} catch (IOException iox) {
JOptionPane.showMessageDialog(null, "Problem with file input");
} finally {
try {
if(br != null) {
br.close();
}
} catch (IOException iox) {
JOptionPane.showMessageDialog(null, "Problem closing the file");
}
}
return split;
//return split[j]; does not work
}
In my while loop, I keep getting compile errors saying it requires a String but found Stirng[] for split. When I try something simpler, such as split[j] = "blah";, there are no compile errors. I can return cancers perfectly but I need to split by the : delimiter and that seems to be something I cant get my head around. When I try return split[j], then I get another compile error saying it requires a String[] but found String. I've been at this for more than an hour, read through examples in my textbook and tutorials online for using split but it still isn't working. This is the only part of my program that I'm not sure how to do.
I tried pasting the entire file but it came a horrid block of text, so here are 2 lines from it. Each line has the same format but differing lengths:
The general format of the file is name : symptoms : causes : treatment : rate : prognosis
The rate is a String since it is unknown for some diseases and when it is known, the rate is not always out of 250,000. Sometimes it is out of 1,000,000 or 100,000, etc... .
acute promyelocytic leukemia : easy bruising, rapid internal bleeding, fatigue, anemia, frequent fever, infection, blood clots : PML and RARA genes : Medications, chemotherapy : 1 in 250,000 : Good
familial cylindromatosis : numerous skin tumours, ulcers, infection, impaired eyesight, hearing, smell, balance : CYLD gene : Surgery, chemotherapy : Unknown : Unknown
My most recent code attempt is at Unusual output from using split()
The 2 arrays of cancers and split are private String[] as field variables declared outside any of the methods. The variable myData is a private File also declared as a field variable outside any of the methods. I have checked and already verified the file path is correct.
The main method that calls the method:
public static void main(String[] args) {
CancerGUI _gui = new CancerGUI();
String[] resultCancer;
resultCancer = _gui.readCancer();
//System.out.println(resultCancer);
System.out.println(Arrays.toString(resultCancer));
}
I am only calling it in the main method to test whether it correctly returns the String[]. Once it does, then I will call it in a different method that adds the data to a GUI (this part I am reasonably confident I know how to do and have examples from my instructor and textbook to follow).
Related
Taking in a list of strings and converting them to a float and storing the values. I get this error when hitting the second value I want to store. Below is the code and the text file I'm reading from:
public static void readCities() {
StringBuilder sb = new StringBuilder();
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("C:/Users/Luke/workspace/Traveling Sales Person/Destinations/11PointDFSBFS.tsp"));
String line;
while ((line = br.readLine()) != null) {
if (sb.length() > 0) {
sb.append("\n");
}
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null) {
br.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
String contents = sb.toString();
String[] parts = contents.split("NODE_COORD_SECTION");//splits into locations
String[] locations = parts[1].split(" ");
int counter = 0;
for (int i = 1; i < locations.length; i++) {
cities[counter] = new City(Float.parseFloat(locations[i+1]), Float.parseFloat(locations[i+2]));
counter++;
}
}
Code error:
Exception in thread "main" java.lang.NumberFormatException: For input string: "63.860370
2
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2043)
at sun.misc.FloatingDecimal.parseFloat(FloatingDecimal.java:122)
at java.lang.Float.parseFloat(Float.java:451)
at TSP.readCities(TSP.java:132)
at TSP.main(TSP.java:28)
As all the commenters already said: Without the actual data it's more or less guessing, what is the problem, but with your code and the error-message some things can be said already, what you should do independly:
You read in all the lines and put them into a StringBuilder including a new line-break. Later on you do splits, but you never remove this line-break, so it is going to end up in the data you try to parse as float. This will lead to a parsing error, because spaces and other whitespaces are not removed. The easiest way to do this without changing too much in your code is by trimming the values:
cities[counter] = new City(Float.parseFloat(locations[i+1].trim()), Float.parseFloat(locations[i+2],trim()));
BTW: What's the reason for creating a new variable counter that is essentially i-1 and using i+1 and i+2 later on? Makes reading your code a bit harder, because you expect some additional logic where entries are skipped which isn't there.
According to the error-message the problem is a leading quotation mark and a newline. You can't say if that error occurred for the first or the second of the two values that are parsed and without the original line(s) of the input file it's hard to say, what is going on, but maybe I gave you enough hints to allow you to progress with your code.
If not we need more informations, especially the line(s) that produce this error, so analysing your code becomes possible.
I am new in java. I just wants to read each string in java and print it on console.
Code:
public static void main(String[] args) throws Exception {
File file = new File("/Users/OntologyFile.txt");
try {
FileInputStream fstream = new FileInputStream(file);
BufferedReader infile = new BufferedReader(new InputStreamReader(
fstream));
String data = new String();
while ((data = infile.readLine()) != null) { // use if for reading just 1 line
System.out.println(""+data);
}
} catch (IOException e) {
// Error
}
}
If file contains:
Add label abc to xyz
Add instance cdd to pqr
I want to read each word from file and print it to a new line, e.g.
Add
label
abc
...
And afterwards, I want to extract the index of a specific string, for instance get the index of abc.
Can anyone please help me?
It sounds like you want to be able to do two things:
Print all words inside the file
Search the index of a specific word
In that case, I would suggest scanning all lines, splitting by any whitespace character (space, tab, etc.) and storing in a collection so you can later on search for it. Not the question is - can you have repeats and in that case which index would you like to print? The first? The last? All of them?
Assuming words are unique, you can simply do:
public static void main(String[] args) throws Exception {
File file = new File("/Users/OntologyFile.txt");
ArrayList<String> words = new ArrayList<String>();
try {
FileInputStream fstream = new FileInputStream(file);
BufferedReader infile = new BufferedReader(new InputStreamReader(
fstream));
String data = null;
while ((data = infile.readLine()) != null) {
for (String word : data.split("\\s+") {
words.add(word);
System.out.println(word);
}
}
} catch (IOException e) {
// Error
}
// search for the index of abc:
for (int i = 0; i < words.size(); i++) {
if (words.get(i).equals("abc")) {
System.out.println("abc index is " + i);
break;
}
}
}
If you don't break, it'll print every index of abc (if words are not unique). You could of course optimize it more if the set of words is very large, but for a small amount of data, this should suffice.
Of course, if you know in advance which words' indices you'd like to print, you could forego the extra data structure (the ArrayList) and simply print that as you scan the file, unless you want the printings (of words and specific indices) to be separate in output.
Split the String received for any whitespace with the regex \\s+ and print out the resultant data with a for loop.
public static void main(String[] args) { // Don't make main throw an exception
File file = new File("/Users/OntologyFile.txt");
try {
FileInputStream fstream = new FileInputStream(file);
BufferedReader infile = new BufferedReader(new InputStreamReader(fstream));
String data;
while ((data = infile.readLine()) != null) {
String[] words = data.split("\\s+"); // Split on whitespace
for (String word : words) { // Iterate through info
System.out.println(word); // Print it
}
}
} catch (IOException e) {
// Probably best to actually have this on there
System.err.println("Error found.");
e.printStackTrace();
}
}
Just add a for-each loop before printing the output :-
while ((data = infile.readLine()) != null) { // use if for reading just 1 line
for(String temp : data.split(" "))
System.out.println(temp); // no need to concatenate the empty string.
}
This will automatically print the individual strings, obtained from each String line read from the file, in a new line.
And afterwards, I want to extract the index of a specific string, for
instance get the index of abc.
I don't know what index are you actually talking about. But, if you want to take the index from the individual lines being read, then add a temporary variable with count initialised to 0.
Increment it till d equals abc here. Like,
int count = 0;
for(String temp : data.split(" ")){
count++;
if("abc".equals(temp))
System.out.println("Index of abc is : "+count);
System.out.println(temp);
}
Use Split() Function available in Class String.. You may manipulate according to your need.
or
use length keyword to iterate throughout the complete line
and if any non- alphabet character get the substring()and write it to the new line.
List<String> words = new ArrayList<String>();
while ((data = infile.readLine()) != null) {
for(String d : data.split(" ")) {
System.out.println(""+d);
}
words.addAll(Arrays.asList(data));
}
//words List will hold all the words. Do words.indexOf("abc") to get index
if(words.indexOf("abc") < 0) {
System.out.println("word not present");
} else {
System.out.println("word present at index " + words.indexOf("abc"))
}
I wrote a program that generates random numbers into two text files and random letters into a third according the two constant files. Now I need to read from each text file, line by line, and put them together. The program is that the suggestion found here doesn't really help my situation. When I try that approach it just reads all lines until it's done without allowing me the option to pause it, go to a different file, etc.
Ideally I would like to find some way to read just the next line, and then later go to the line after that. Like maybe some kind of variable to hold my place in reading or something.
public static void mergeProductCodesToFile(String prefixFile,
String inlineFile,
String suffixFile,
String productFile) throws IOException
{
try (BufferedReader br = new BufferedReader(new FileReader(prefixFile)))
{
String line;
while ((line = br.readLine()) != null)
{
try (PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(productFile, true))))
{
out.print(line); //This will print the next digit to the right
}
catch (FileNotFoundException e)
{
System.err.println("File error: " + e.getMessage());
}
}
}
}
EDIT: The digits being created according to the following. Basically, constants tell it how many digits to create in each line and how many lines to create. Now I need to combine these together without deleting anything from either text file.
public static void writeRandomCodesToFile(String codeFile,
char fromChar, char toChar,
int numberOfCharactersPerCode,
int numberOfCodesToGenerate) throws IOException
{
for (int i = 1; i <= PRODUCT_COUNT; i++)
{
int I = 0;
if (codeFile == "inline.txt")
{
for (I = 1; I <= CHARACTERS_PER_CODE; I++)
{
int digit = (int)(Math.random() * 10);
try (PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(codeFile, true))))
{
out.print(digit); //This will print the next digit to the right
}
catch (FileNotFoundException e)
{
System.err.println("File error: " + e.getMessage());
System.exit(1);
}
}
}
if ((codeFile == "prefix.txt") || (codeFile == "suffix.txt"))
{
for (I = 1; I <= CHARACTERS_PER_CODE; I++)
{
Random r = new Random();
char digit = (char)(r.nextInt(26) + 'a');
digit = Character.toUpperCase(digit);
try (PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(codeFile, true))))
{
out.print(digit);
}
catch (FileNotFoundException e)
{
System.err.println("File error: " + e.getMessage());
System.exit(1);
}
}
}
//This will take the text file to the next line
if (I >= CHARACTERS_PER_CODE)
{
{
Random r = new Random();
char digit = (char)(r.nextInt(26) + 'a');
try (PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(codeFile, true))))
{
out.println(""); //This will return a new line for the next loop
}
catch (FileNotFoundException e)
{
System.err.println("File error: " + e.getMessage());
System.exit(1);
}
}
}
}
System.out.println(codeFile + " was successfully created.");
}// end writeRandomCodesToFile()
Being respectfull with your code, it will be something like this:
public static void mergeProductCodesToFile(String prefixFile, String inlineFile, String suffixFile, String productFile) throws IOException {
try (BufferedReader prefixReader = new BufferedReader(new FileReader(prefixFile));
BufferedReader inlineReader = new BufferedReader(new FileReader(inlineFile));
BufferedReader suffixReader = new BufferedReader(new FileReader(suffixFile))) {
StringBuilder line = new StringBuilder();
String prefix, inline, suffix;
while ((prefix = prefixReader.readLine()) != null) {
//assuming that nothing fails and the files are equals in # of lines.
inline = inlineReader.readLine();
suffix = suffixReader.readLine();
line.append(prefix).append(inline).append(suffix).append("\r\n");
// write it
...
}
} finally {/*close writers*/}
}
Some exceptions may be thrown.
I hope you don't implement it in one single method.
You can make use of iterators too, or a very simple reader class (method).
I wouldn't use List to load the data at least I guarantee that the files will be low sized and that I can spare the memory usage.
My approach as we discussed by storing the data and interleaving it. Like Sergio said in his answer, make sure memory isn't a problem in terms of the size of the file and how much memory the data structures will use.
//the main method we're working on
public static void mergeProductCodesToFile(String prefixFile,
String inlineFile,
String suffixFile,
String productFile) throws IOException
{
try {
List<String> prefix = read(prefixFile);
List<String> inline = read(inlineFile);
List<String> suffix = read(productFile);
String fileText = interleave(prefix, inline, suffix);
//write the single string to file however you want
} catch (...) {...}//do your error handling...
}
//helper methods and some static variables
private static Scanner reader;//I just prefer scanner. Use whatever you want.
private static StringBuilder sb;
private static List<String> read(String filename) throws IOException
{
List<String> list = new ArrayList<String>;
try (reader = new Scanner(new File(filename)))
{
while(reader.hasNext())
{ list.add(reader.nextLine()); }
} catch (...) {...}//catch errors...
}
//I'm going to build the whole file in one string, but you could also have this method return one line at a time (something like an iterator) and output it to the file to avoid creating the massive string
private static String interleave(List<String> one, List<String> two, List<String> three)
{
sb = new StringBuilder();
for (int i = 0; i < one.size(); i++)//notice no checking on size equality of words or the lists. you might want this
{
sb.append(one.get(i)).append(two.get(i)).append(three.get(i)).append("\n");
}
return sb.toString()
}
Obviously there is still some to be desired in terms of memory and performance; additionally there are ways to make this slightly more extensible to other situations, but it's a good starting point. With c#, I could more easily make use of the iterator to make interleave give you one line at a time, potentially saving memory. Just a different idea!
I have to make an EPG app using java, but I am kind of new in programming and it's due tomorrow and it's still not working properly.
I have a question about a small part: I have to read the programs from a text file. Each line contains multiple things, the channel, the title of the program, a subtitle, a category, etcetera.
I have to make sure that I can read the separate parts of each line, but it's not really working, it's only printing the parts from the first line.
I am trying, but I can't find why it's not printing all the parts from all the lines in stead of printing only the parts from the first line. Here's the code:
BufferedReader reader = new BufferedReader(newFileReader(filepath));
while (true) {
String line = reader.readLine();
if (line == null) {
break;
}
}
String[] parts = line.split("\\|", -1);
for(int i = 0; i < parts.length; i++) {
System.out.println(parts[i]);
}
reader.close();
Does anybody know how to get all the lines in stead of only the first?
Thank you!
readLine() only reads one line, so you need to loop it, as you said.
BUT with reading to the String inside of the while loop you always overwrite that String.
You would need to declare the String above the while loop that you can access it from outside, too.
BTW, it seems that your braces for the if don't match.
Anyway, I'd fill the information into an ArrayList, look below:
List<String> list = new ArrayList<>();
String content;
// readLine() and close() may throw errors, so they require you to catch it…
try {
while ((content = reader.readLine()) != null) {
list.add(content);
}
reader.close();
} catch (IOException e) {
// This just prints the error log to the console if something goes wrong
e.printStackTrace();
}
// Now proceed with your list, e.g. retrieve first item and split
String[] parts = list.get(0).split("\\|", -1);
// You can simplify the for loop like this,
// you call this for each:
for (String s : parts) {
System.out.println(s);
}
Use apache commons lib
File file = new File("test.txt");
List<String> lines = FileUtils.readLines(file);
As ArrayList is Dynamic,try,
private static List<String> readFile(String filepath) {
String line = null;
List<String> list = new ArrayList<String>();
try {
BufferedReader reader = new BufferedReader(new FileReader(filepath));
while((line = reader.readLine()) != null){
list.add(line);
}
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
I have written some code to read in Vehicle data from a .txt file. At the moment I can read in all the data correctly and create the objects fine. I have a while loop that checks for the text "Vehicle Details" in the file and if it is present (i.e. there is another vehicle to add) it enters the loop to add the data.
The problem is that when there isn't anymore data the readLine() method is still called and this creates a NullPointerException (at least that's what I think is the cause)
Here is the method in use.
public static void addNewVehicleFromFile(Showroom s)
{
try
{
FileInputStream fStream = new FileInputStream("AddVehicleFromFile.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fStream));
String stringLine;
while ((stringLine = br.readLine()).equalsIgnoreCase("Vehicle Details"))
{
System.out.println("P1");//Testing
br.readLine();
String[] manufacturer = br.readLine().split(" =");
String[] model = br.readLine().split(" =");
String[] vin = br.readLine().split(" =");
String[] dateOfMan = br.readLine().split(" =");
String[] taxBand = br.readLine().split(" =");
String[] cost = br.readLine().split(" =");
System.out.println("P2");//Testing
System.out.println(manufacturer[0].toString());
System.out.println(model[0].toString());
System.out.println(vin[0].toString());
System.out.println(dateOfMan[0].toString());
System.out.println(taxBand[0].toString());
br.readLine();
System.out.println("P3");//Testing
int strToInt = Integer.parseInt(cost[0]);
Vehicle inputVehicle = new Vehicle(manufacturer[0], model[0], vin[0], dateOfMan[0],
taxBand[0].charAt(0), strToInt);
System.out.println("P4");//Testing
s.addVehicle(inputVehicle);
System.out.println("P5");//Testing
}
}
catch (FileNotFoundException fnfe)
{
System.out.println("File not found exception: " + fnfe.toString());
}
catch (IOException ioe)
{
System.out.println("I/O exception: " + ioe.toString());
}
System.out.println("addNewVehicleFromFile Complete");
}
Not sure if you need it but here is my file data.
Vehicle Details
Fordtest =manufacturer
Focus =model
ioCheck =VIN
09/01/1989 =DateOfMan
d =TaxBand
19900 =Cost
Vehicle Details
Fordtest2 =manufacturer
Focus2 =model
ioCheckVIN2 =VIN
09/01/1989 =DateOfMan
a =TaxBand
1922 =Cost
Finally, to make it clear where the program runs to I have added in some console output as testing. The while loops iterates twice outputting p1-p5 both times before the error occurs and it never reaches the final console output saying the method is complete.
Check that the result of calling readLine() is not null (empty). If you check, and cause it not to do anything if its empty, this will solve your issue!
Try checking if readLine() is null.
while ((stringLine = br.readLine()) != null) { }
This will make sure that there is something in that line to read, else it has reached end of file.
In your code you have 3 calls to readLine() each iteration. This could cause issues if for some reason the formatting in your text file is changed(missing a blank line for example). You may be better off making each vehicle on one line, seperated by commas. For example:
Vehicle Details
Fordtest =manufacturer
Focus =model
ioCheck =VIN
09/01/1989 =DateOfMan
d =TaxBand
19900 =Cost
Vehicle Details
Fordtest2 =manufacturer
Focus2 =model
ioCheckVIN2 =VIN
09/01/1989 =DateOfMan
a =TaxBand
1922 =Cost
Then becomes:
Fordtest, Focus, ioCheck, 09/01/1989, d, 19900
Fordtest2, Focus2, ioCheckVIN2, 09/01/1989, a, 1922
This would simplify the code somewhat, as well as reducing chance for error.
Also make sure to close the FileInputStream when you are finished with it. This insures that any resources associated with it are released properly.
try {
FileInputStream fStream = new FileInputStream("AddVehicleFromFile.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fStream));
...
} finally {
try {
if (fStream != null) {
fStream.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}