This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
When i tried to run this program, it only show "Beginning of Read-in records list. But the program doesnt terminate, which means the program keep running, but it doesnt output anything. Could anyone please help?
public static void readFile(String fileName, PhoneBook book_list)
{
if(fileName == null) return;
File file = new File(fileName);
if(!file.isFile())
{
System.out.println("File not found!");
return ;
}
Person person = new Person();
boolean invalid = false;
System.out.println("\nInfo: Beginning of Read-in records list.\n");
try
{
BufferedReader input = new BufferedReader(new FileReader(file));
try
{
String line = "";
line = input.readLine();
while(line != null)
{
line = line.trim();
String[] words = line.split("\\s+");
if(invalid)
{
if(words[0].equals(""))
{
person = new Person();
invalid = false;
}
}
//refer to end of a record
else if(words[0].equals(""))
{
if(person.validation())
{
book_list.addPerson(person);
person = new Person();
}
else
{
person = new Person();
}
}
if(words[0].equalsIgnoreCase("name"))
{
if(words.length<2)
{
invalid=true;
}
else
{
String name = words[1];
for(int i=2; i<words.length;i++)
{
name = name + " " + words[i];
}
for(int i=0; i<name.length(); i++)
{
if((name.codePointAt(i) >= 97 && name.codePointAt(i) <= 122)/*a-z*/
|| (name.codePointAt(i) >= 65 && name.codePointAt(i) <= 90)/*A-z*/
|| name.codePointAt(i) == 32)/*space*/
{continue;}
else
{
invalid=true;
break;
}
}
if(!invalid)
{
person.setName(name);
}
}
}
else if(words[0].equalsIgnoreCase("birthday"))
{
if(words.length !=2)
{
invalid=true;
}
else
{
try
{
person.setBirthday(words[1]);
book_list.addPerson(person);
}
catch (ParseException e)
{
invalid = true;
}
}
}
else if(words[0].equalsIgnoreCase("phone"))
{
if(words.length != 2)
{
invalid = true;
}
else
{
String phone = Tools.parsePhone(words[1]);
if(phone!=null)
{
person.setPhone(phone);
}
else
{
invalid = true;
}
}
}
else if(words[0].equalsIgnoreCase("email"))
{
if(words.length != 2)
{
invalid = true;
}
else
{
if(Tools.validateEmail(words[1]))
{
person.setEmail(words[1]);
}
else
{
invalid = true;
}
}
}
else if(words[0].equalsIgnoreCase("address"))
{
String address = line.substring(words[0].length()).trim();
String addr="";
do
{
line = input.readLine();
if(line == null)
{
person.setAddress(address);
}
if(!invalid && person.validation())
{
book_list.addPerson(person);
}
addr = line.trim();
String[] adds = addr.split("\\s+");
if(!adds[0].equals("")
&& !adds[0].equalsIgnoreCase("name")
&& !adds[0].equalsIgnoreCase("birthday")
&& !adds[0].equalsIgnoreCase("phone")
&& !adds[0].equalsIgnoreCase("email")
&& !adds[0].equalsIgnoreCase("address"))
{
address = address + " " + addr;
}
else break;
}
while(true);
if(line == null)
break;
}
}// end of while loop
}
finally
{
input.close();
}
}
catch(IOException ex)
{
System.err.print("Error: Open records file failed");
return;
}
System.out.println("\nInfo: End of Read-in records list.\n");
return;
}
public static void main(String[] args)
{
String personFile = null; // person contact information file
String instFile = null; //instruction file
String outputFile = null; //output file name;
String reportFile = null; //report file name;
PhoneBook book_list = new PhoneBook();
FileIO2.readFile("C:/Users/phoenix/Desktop/sample_phonebook1.txt", book_list);
ArrayList<Person> a;
a = book_list.getPersonList();
System.out.println(a.size());
}
I think your problem is here:
// initializes "line" String
String line = "";
// Tells BufferedReader to read one line (the first line)
line = input.readLine();
// loops infinitely since String read from first line is not null in this specific case
while(line != null)
{
...
Try this:
// initializes "line" String
String line = "";
// tells the BufferedReader to read a new line _until_ the new line is null
// ... if new line is null we reached EOF
while ((line = input.readLine() != null) {
...
You should do:
String line = null;
while ((line = input.readLine()) != null) {
...
...
}
Instead of:
String line = "";
line = input.readLine();
while(line != null){
...
...
}
Keep reading files. Cheers! :P
You have used while & do..while loop..
And you are not reading file properly
after do..while you should include line = input.readLine()
Related
This question already has answers here:
Find location of a removable SD card
(24 answers)
Closed 4 years ago.
I need SdCard path to save files in it. I have tried some codes but these code didn't work on some devices or Android versions. Now I need a code/path that get SdCard path for all device and all Android versions.
For getting sdcard path,try following code:
public static String getExternalSDCardRootDirectory() {
String cmdMOUNT = "cat /proc/mounts";
Runtime run = Runtime.getRuntime();
List<String> paths = new ArrayList<>();
try {
Process p = run.exec(cmdMOUNT);
BufferedInputStream in = new BufferedInputStream(p.getInputStream());
BufferedReader inBr = new BufferedReader(new InputStreamReader(in));
String lineStr;
while ((lineStr = inBr.readLine()) != null) {
Log.d(TAG, lineStr);
if (lineStr.toLowerCase().contains("sdcard") || lineStr.toLowerCase().contains("ext") ) {
String[] strArray = lineStr.split(" ");
if (strArray.length >= 3 &&
(!strArray[1].contains("/system") &&
!strArray[1].contains("/data") &&
!strArray[1].contains("/cache") &&
!strArray[1].contains("/persist")
)) {
String result = strArray[1].trim();
if((result.contains("ext") || result.contains("1")) && result.contains("storage")) {
paths.add(result);
}
//return result;
}
}
if (p.waitFor() != 0 && p.exitValue() == 1) {
Log.e(TAG, "check mount info failed");
return null;
}
}
inBr.close();
in.close();
} catch (Exception e) {
e.printStackTrace();
return null;
}
if (paths.size() > 0) {
return paths.get(0);
}
else {
return null;
}
}
For getting path you need to call Environment.getExternalStorageState()
I've found an existing post.
Simply change it to...
public static HashSet<String> getExternalMounts() {
final HashSet<String> out = new HashSet<String>();
String reg = "(?i).*vold.*(vfat|ntfs|exfat|fat32|ext3|ext4).*rw.*";
String s = "";
try {
final Process process = new ProcessBuilder().command("mount")
.redirectErrorStream(true).start();
process.waitFor();
final InputStream is = process.getInputStream();
final byte[] buffer = new byte[1024];
while (is.read(buffer) != -1) {
s = s + new String(buffer);
}
is.close();
} catch (final Exception e) {
e.printStackTrace();
}
// parse output
final String[] lines = s.split("\n");
for (String line : lines) {
if (!line.toLowerCase(Locale.US).contains("asec")) {
if (line.matches(reg)) {
String[] parts = line.split(" ");
for (String part : parts) {
if (part.startsWith("/"))
if (!part.toLowerCase(Locale.US).contains("vold"))
out.add(part);
}
}
}
}
return out;
}
The tested solution on different platforms can be found here.
I created a java file called Product.java. I also created a text file called Items.txt. Basically when the user enter the word using sequential search to search the data what they are looking from Items.txt. My main problem is when I enter 3 to display all the records or enter x to exit the program, it keeps on looping. But I don't how to resolve this problem. Can anyone solved this for me?
Items.txt
1000|Cream of Wheat|Normal Size|Breakfast|NTUC|5|3.00
1001|Ayam Brand|Small Size|Canned|NTUC|4|4.00
Product.java
import java.io.*;
import java.util.*;
public class Product {
public static void main(String[] args) {
ArrayList<Item> prdct = new ArrayList<Item>();
String inFile = "items.txt";
String line = "";
FileReader fr = null;
BufferedReader br = null;
StringTokenizer tokenizer;
int quantity;
String id, brandname, desc, category, supplier;
float price;
try{
fr = new FileReader(inFile);
br = new BufferedReader(fr);
line = br.readLine();
while(line!=null)
{
tokenizer = new StringTokenizer(line,"|");
id = tokenizer.nextToken();
brandname = tokenizer.nextToken();
desc = tokenizer.nextToken();
category = tokenizer.nextToken();
supplier = tokenizer.nextToken();
quantity = Integer.parseInt(tokenizer.nextToken());
price = Float.parseFloat(tokenizer.nextToken());
Item itm = new Item(id,brandname,desc,category,supplier,quantity,price);
prdct.add(itm);
line = br.readLine();
}
br.close();
}
catch(FileNotFoundException e){
System.out.println("The file " + inFile + " was not found.");
}
catch(IOException e){
System.out.println("Reading error!");
}
finally
{
if (fr!=null){
try
{
fr.close();
}
catch(IOException e)
{
System.out.println("Error closing file!");
}
}
}
String INPUT_PROMPT = "\nPlease enter 3 to display all records, 4 to insert record, 5 to remove old records " + "or enter 'x' to quit.";
System.out.println(INPUT_PROMPT);
try
{
BufferedReader reader = new BufferedReader
(new InputStreamReader (System.in));
line = reader.readLine();
while(reader != null)
{
for(int i=0; i<prdct.size(); i++)
{
if(prdct.get(i).id.contains(line) || prdct.get(i).brandname.contains(line) || prdct.get(i).desc.contains(line)
|| prdct.get(i).category.contains(line) || prdct.get(i).supplier.contains(line))
{
System.out.println(prdct.get(i));
}
System.out.println(INPUT_PROMPT);
line = reader.readLine();
}
}
while("3".equals(line))
{
for(int i=0; i<prdct.size(); i++)
{
System.out.println(prdct.get(i));
}
System.out.println(INPUT_PROMPT);
line = reader.readLine();
}
while(!line.equals("x"))
{
System.out.println(INPUT_PROMPT);
line=reader.readLine();
}
}
catch(Exception e){
System.out.println("Input Error!");
}
}
}
The problem is with this loop:
while(reader != null)
{
for(int i=0; i<prdct.size(); i++)
{
if(prdct.get(i).id.contains(line) || prdct.get(i).brandname.contains(line) || prdct.get(i).desc.contains(line)
|| prdct.get(i).category.contains(line) || prdct.get(i).supplier.contains(line))
{
System.out.println(prdct.get(i));
}
System.out.println(INPUT_PROMPT);
line = reader.readLine();
}
}
It keeps on looping while reader is not null and it will never be. You might want to try checking something else that suits your problem better, maybe:
While(!line.equals("3"))
While(!line.equals("x"))
While(line != null)
Otherwise, even if there is an 'x', '3' or simply nothing, still (reader != null) and therefore the loop is infinite.
I suspect that the newline character is what causes the comparison to fail.
Instead of checking if:
"3".equals(line)
Try:
"3".equals(line.trim())
Same applies to the following comparison.
Try changing this..
line = reader.readLine();
while(reader != null)
{
to this..
line = reader.readLine();
while(line != null)
{
You are looping on the reader being not null, which it always will be.
you have to define these functions:
public void showAllRecords() {
// show all record here
}
public void insertRecord() {
// insert record here
}
public void removeRecord() {
// insert record here
}
public void exit() {
// insert record here
}
then
do{
System.out.println(INPUT_PROMPT);
switch(line)
{
case "3":
showAllRecords();
break;
case "4":
insertRecord();
break;
case "5":
removeRecord();
}
}while(!line.equals('x'));
How can i ignore the comment statements that begin with "/*" and ends with
"*/" for example: /*the problem is..*/ or
/* problem is very difficult */ ,,i want to remove these statement when i reading java file line by line
public class filename1 {
public static void main (String args[])
{
try {
fileName = "C:\\NetBeansProjects\\filename\\src\\filename\\filename.java";
FileReader fr = new FileReader(fileName);
BufferedReader br = new BufferedReader(fr);
line = br.readLine();
while (line !=null) {
for( int i=0;i<line.length();i++)
{
b=line.indexOf("/",i);
ee=line.indexOf("*",i);
if(b!=-1 && ee!=-1)
v=line.indexOf("*/",i);
if (v==-1)
line=" ";
}
System.out.println(line);
line = br.readLine();
}}
catch (IOException e)
{
e.printStackTrace();
}
}
}
Simply include:
int index = str.indexOf("/*");
while(index != -1) {
str = str.substring(0, index) + str.substring(str.indexOf("*/")+2);
index = str.indexOf("/*");
}
Edit:
Assuming that you have to account for fragments where you have a comment interrupted by the start or end of the string:
Edit2:
Now.. Also assuming that you have to take into account for literal string "/*" or "*/"
str = str.replace("\"/*\"", "literal_string_open_comment");
str = str.replace("\"*/\"", "literal_string_close_comment");
int start = str.indexOf("/*"), end = str.indexOf("*/");
while(start > -1 || end > -1) {
if(start != -1) {
if(end != -1) {
if(end < start) {
str = str.substring(end+2);
} else {
str = str.substring(0, start) + str.substring(end+2);
}
} else {
str = str.substring(0, start);
}
} else {
str = str.substring(end+2);
}
start = str.indexOf("/*");
end = str.indexOf("*/");
}
str = str.replace("literal_string_open_comment", "\"/*\"");
str = str.replace("literal_string_close_comment", "\"*/\"");
I have written code of dictionary in java in which i read data from file named newFile.txt .In file world is placed on one line and its meaning is placed on nextline. User enters a world. If word is found in file it shows its meaning placed on next line and if word is not found it shows similar words (substrings).
"While searching word it should not search meaning."
import java.io.*;
import java.util.*;
public class Notepad {
public static void main(String []args) throws IOException{
BufferedReader in = null;
Scanner input = new Scanner(System.in);
String str;
boolean notfound = false;
char again = 'a';
try{
do{
notfound = false;
System.out.println("Enter word :");
str = input.next();
File f = new File("D:\\newFile.txt");
in = new BufferedReader(new FileReader(f));
String s;
while((s = in.readLine()) != null){
int x = s.indexOf(str);
if(x != -1){
int lens = s.length();
String sub = s.substring(x);
int lensub = str.length();
if(lens == lensub){
System.out.println((in.readLine()));
break;
}
else{
System.out.println(sub) ;
notfound = true;
}
}
s = in.readLine();
}
if(!notfound){
System.out.println("Try another world?(y/n):");
again = input.next().trim().charAt(0);
again = Character.toLowerCase(again);
}
}
while(notfound || again == 'y');
System.out.println("terminated!");
}
finally{
if(in != null){
in.close();
}
}
}
}
when i enters a substring of a word it searches meaning as well and then if a enter right word it does not show meaning
//This code is reading a file that is situated like this:
Hello - to greet
Circle - a round shape
//Then the code can be done like so, is this ok?
public static void main(String []args) throws IOException{
BufferedReader in = null;
Scanner input = new Scanner(System.in);
String str;
boolean notfound = false;
char again = 'a';
try{
do{
notfound = false;
System.out.println("Enter word :");
str = input.next();
File f = new File("/Folder/demo1.txt");
in = new BufferedReader(new FileReader(f));
String s;
while((s = in.readLine()) != null){
int x = s.indexOf(str);
// System.out.println("Index of dash:" + s.indexOf("-"));
// System.out.println("Index of Hello:" + x);
if(x != -1 && x<s.indexOf("-")){
String sub = s.substring(0,s.indexOf("-"));
System.out.println("Sub:" + sub);
System.out.println("Str:" + str);
if(sub.trim().equals(str.trim())){
System.out.println("Success:" +sub);
notfound = true;
break;
}
else{
System.out.println("Word is not present") ;
notfound = false;
break;
}
}
}
if(!notfound){
System.out.println("Try another word?(y/n):");
again = input.next().trim().charAt(0);
again = Character.toLowerCase(again);
}
}
while(notfound || again == 'y');
System.out.println("terminated!");
}
finally{
if(in != null){
in.close();
}
}
}
}
I keep getting this error
java.util.NoSuchElementException No line found
when I use this method
public boolean hasMoreCommands() {
if (input.hasNextLine()) {
return true;
} else {
//input.close();
return false;
}
}
public void advance() {
String str;
if(hasMoreCommands() == true){
do {
str = input.nextLine().trim();
// Strip out any comments
if (str.contains("//")) {
str = (str.substring(0, str.indexOf("//"))).trim();
}
} while (str.startsWith("//") || str.isEmpty() || hasMoreCommands());
command = str;
}
}
I have main code here:
public class Ptest
{
public Ptest(String fileName)
{
String line = null;
String nName = fileName.replace(".vm", ".asm");
Parser p = new Parser();
try{
File neF = new File(nName);
if(!neF.exists()){
neF.createNewFile();
}
File tempFile = new File("temp.txt");
if(!tempFile.exists()){
tempFile.createNewFile();
}
FileReader fr = new FileReader(fileName);
BufferedReader br = new BufferedReader(fr);
FileWriter fw = new FileWriter(nName);
BufferedWriter bw = new BufferedWriter(fw);
FileWriter writR = new FileWriter(tempFile);
BufferedWriter buffR = new BufferedWriter(writR);
while((line = br.readLine()) != null) {
buffR.write(line+ "\n");
//System.out.println(line);
}
buffR.flush();
buffR.close();
p.insertTitle(tempFile);
String ctype = p.commandType();
int len = ctype.length();
int spaces = 13 - len;
String sp = " ";
String asp = " ";
String a1 = null;
int a2;
int alen;
boolean t = false;
while(p.hasMoreCommands()){
for(int i= 0; i < spaces; i++){
sp += " ";
}
t = p.hasMoreCommands();
a1 = p.arg1();
alen = (10 - a1.length());
for(int i= 0; i < alen; i++){
asp += " ";
}
//a2 = p.arg2();
if (ctype == "C_PUSH" || ctype == "C_POP" || ctype == "C_FUNCTION" || ctype == "C_CALL") {
a2 = p.arg2();
bw.write(ctype + sp + a1 + asp + a2);
}
else {
bw.write(ctype + sp + a1);
}
p.advance();
ctype = p.commandType();
len = ctype.length();
spaces = 13 - len;
}
bw.flush();
bw.close();
}
catch(FileNotFoundException ex){
System.out.println("File not found!");
}
catch(IOException ex){
System.out.println("Error reading file '" + fileName + "'");
}
}
}
I went through debugger and it literally goes the entire file then gives me an error when its finished.
Like #hfontanez I think your problem is in this code:
if(hasMoreCommands() == true){
do {
str = input.nextLine().trim();
// Strip out any comments
if (str.contains("//")) {
str = (str.substring(0, str.indexOf("//"))).trim();
}
} while (str.startsWith("//") || str.isEmpty() || hasMoreCommands());
command = str;
}
However, my solution is to change the while clause to while (str.isEmpty() && hasMoreCommands());
I'm assuming that "advance" ought to return the next non-comment / blank line.
If the string from the previous pass is empty (after stripping any comment) it will go round the loop again provided that wasn't the last line. But, if that was the last line or str still has something in it, then it will exit the loop. Comments should have been stripped so don't need tested for in the while.
I think if you just test for hasNextLine within the loop then it will never exit the loop if the last line was comment / blank.
My guess is that your problem is here:
if(hasMoreCommands() == true){
do {
str = input.nextLine().trim();
// Strip out any comments
if (str.contains("//")) {
str = (str.substring(0, str.indexOf("//"))).trim();
}
} while (str.startsWith("//") || str.isEmpty() || hasMoreCommands());
command = str;
}
The exception you encountered (NoSuchElementException) typically occurs when someone tries to iterate though something (String tokens, a map, etc) without checking first if there are any more elements to get. The first time the code above is executed, it checks to see if it has more commands, THEN it gets in a loop. The first time it should work fine, however, if the test done by the while() succeeds, the next iteration will blow up when it tries to do input.nextLine(). You have to check is there is a next line to be got before calling this method. Surround this line with an if(input.hasNextLine()) and I think you should be fine.