Scanner cannot be resolved [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
File inputTXT = new File (fileName);
try{
Scanner in = new Scanner(inputTXT);
}catch(FileNotFoundException e){
System.out.println("");
}
while(in.hasNext()){
String line = in.nextLine();
It says in can't be resolved.How am I going to fix this problem?
I've tried ignored try catch block, but this file scanner has to be in the try catch block

In your code you have issue about variable scope.You defined in variable in try catch block and then you used it in while loop.It should be like below:
File inputTXT = new File (fileName);
Scanner in=null;
try{
in = new Scanner(inputTXT);
}catch(FileNotFoundException e){
System.out.println("");
}
while(in.hasNext()){
String line = in.nextLine();

Related

Get the list of all URLs on the website using Java [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
There are many libraries(eg. Jsoup) which can do this task in a go but how can I get all the URLs present in the HTML content of any website using Java without using any external libraries?
Edit 1: Can anyone explain what scanner.useDelimiter("\Z") actually does and what is the difference between scanner.useDelimiter("\Z") and scanner.useDelimiter("\z").
I am answering my own question as I was trying to find the accurate answer on StackOverflow but couldn't find one.
Here is the code:
URL url;
ArrayList<String> finalResult = new ArrayList<String>();
try {
String content = null;
URLConnection connection = null;
try {
connection = new URL("https://yahoo.com").openConnection();
Scanner scanner = new Scanner(connection.getInputStream());
scanner.useDelimiter("\\Z");
content = scanner.next();
scanner.close();
} catch (Exception ex) {
ex.printStackTrace();
}
String regex = "(https?|ftp|file)://[-a-zA-Z0-9+&##/%?=~_|!:,.;]*[-a-zA-Z0-9+&##/%=~_|]";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(content);
while (m.find()) {
if(!finalResult.contains((m.group())))
finalResult.add(m.group());
}
} finally {
for(String res: finalResult){
System.out.println(res);
}
}
You can try using a regEx.
Here is an example of a regEx that checks if any test is a URL or not.
https://www.regextester.com/96504.
But I can't stop my self to say that Jsoup is what fits for this. but it's an external library.

how to read the number of columns in text file in java [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
how to read the number of columns in text file in java.
Example text file as below. Comma separated. In this i need to get the total column as count 4
ABC,BBC,12-10-2018,1234
ABC,BBC,12-10-2018,1234
ABC,BBC,12-10-2018,1234
ABC,BBC,12-10-2018,1234
The simplest way is to use a Scanner and read the 1st line.
By using split() with , as a delimeter you get an array and its length is what you want.
public static int getFileColumnsNumber(String filename) {
File file = new File(filename);
Scanner scanner;
try {
scanner = new Scanner(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
return -1;
}
int number = 0;
if (scanner.hasNextLine()) {
number = scanner.nextLine().split(",").length;
}
scanner.close();
return number;
}
public static void main(String[] args) {
String filename = "test.txt";
System.out.println(getFileColumnsNumber(filename));
}

java how to catch an exception in main? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I need to read lines from an input path (file).
to do so the main calls a class that uses BufferedReader , it iterates over each line and adds it to an Array.
the problem is:
I want to catch all exceptions thrown from the method in the class in the main.
public static void main (String[] args){
if (args.length != 2){
System.err.print("ERROR");
return;
}
MyFileScript.sourceDir = args[SOURCE_DIR_INDEX];
MyFileScript.commandFile = args[COMMAND_INDEX];
try (FileReader file = new FileReader(MyFileScript.commandFile);
BufferedReader reader = new BufferedReader(file)){
fileParsing = new CommandFileParser(reader);
sectionList = fileParsing.parseFile();
}catch (FileNotFoundException error){
System.err.print(ERROR_MESSAGE);
return;
}catch(IOException error){
System.err.print(ERROR_MESSAGE);
return;
}catch(ErrorException error){
System.err.print(error.getMessage());
return;
}
}
public class CommandFileParser {
public CommandFileParser (BufferedReader reader){
this.reader = reader;
}
/**
* read all lines from a file.
*
* #return a string array containing all file lines
*/
public String[] readFileLines(){
ArrayList<String> fileLines = new ArrayList<String>();
String textLine;
while ((textLine = this.reader.readLine()) != null){
fileLines.add(textLine);
}
String[] allFileLines = new String[fileLines.size()];
fileLines.toArray(allFileLines);
return allFileLines;
}
in the while loop I get a compilation error for unhandling the IOException.
How can I catch all exceptions in main,
and so the class takes only one string argument?
your readFileLines method is lacking a throws clause.
public String[] readFileLines() throws IOException {

Alternate code for Throws IOException [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
What changes do I need to make in the code If I remove the line "throws IOException"??
import java.io.*;
class Buffered_class{
public static void main(String[] args)
throws IOException // remove this line
{
char c;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter characters, 'q' to quit");
do{
c= (char)br.read();
System.out.println(" you entered : " + c );
}while(c !='q');
}
}
You need to catch the exception
import java.io.*;
class Buffered_class{
public static void main(String[] args)
{
char c;
try{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter characters, 'q' to quit");
do{
c= (char)br.read();
System.out.println(" you entered : " + c );
}while(c !='q');
}catch(IOException e){
// do something
}finally{
br.close();
}
}

java.io.File getting extra char while writing into file [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 8 years ago.
Improve this question
Why I am getting extra char while writing into file for the following code? If I am using writeBytes(String) than the below code is working file. Then what is the problem with dos.writeChars() method?
File fileObj = new File("student.txt");
try {
// writing into file
FileOutputStream fos = new FileOutputStream(fileObj);
String msg = "This is student file";
DataOutputStream dos = new DataOutputStream(fos);
dos.writeChars(msg);
//reading from file
FileInputStream fis = new FileInputStream(fileObj);
DataInputStream dis = new DataInputStream(fis);
System.out.println(dis.readLine());
for (int i = 0; ((i = dis.read()) != -1); i++) {
System.out.println(i);
}
fos.close();
dos.close();
} catch (FileNotFoundException e) {
System.err.println("File not found!");
} catch (IOException e) {
e.printStackTrace();
}
writeChars() uses 2-byte chars (UTF-16). So each char you write will result in two bytes written.
If you want another encoding use getBytes() on the String and write it as bytes.

Categories