So I'm new to java and I have to read strings, doubles, and integers from a file and print them out after. This is the error that java is throwing at me:
error: variable declaration not allowed here Scanner file = new
Scanner(line);
what am does it mean?
Scanner file = new Scanner(line);
Fails because a variable named file is already declared above ...
Scanner file = new Scanner(data);
Give one of the scanner variables a different name. There's some other problems with your code, but I assume this is a school assignment so only answered the question you asked.
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("test.txt"));
String line;
while ((line = br.readLine()) != null) {
String[] splited = line.split(" ");
for (String st: splited) {
if(isInteger(st))
System.out.println("---int--->"+st);
else if(isDouble(st))
System.out.println("---dubl--->"+st);
else if (!st.isEmpty())
System.out.println("---String--->"+st);
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null) {
br.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
private static boolean isInteger(String st) {
try {
Integer.parseInt(st);
return true;
} catch (NumberFormatException e) {
return false;
}
}
static boolean isDouble(String str) {
try {
Float.parseFloat(str);
return true;
} catch (NumberFormatException e) {
return false;
}
}
This Maybe help you
Related
Here is my problem.I've made simple input class with methods for getting primitive values from user's keyboard.The problem is that whenever i use this class in my other classes i face the problem that when i made more than one instance of this class i get a problem of the "Close stream".Why is this happening?
For example:i have a main method where i get user's input and decide which object to make,say i can make 4 different objects(4 classes),after i call the objects "set state" method,where i actually set all the states of this object with making second instance of the input class,and then ,when i try to read again the user's input in my main method,i get an exception "Stream closed".
Here is the code of the input class :
public class UserInput {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));;
public int getInt() {
try {
String line;
line = reader.readLine();
return Integer.parseInt(line);
} catch (Exception ex) {
ex.printStackTrace();
return -1;
}
}
public double getDouble() {
try {
String line = reader.readLine();
return Double.parseDouble(line);
} catch (Exception ex) {
return -1;
}
}
public float getFloat() {
try {
String line = reader.readLine();
return Float.parseFloat(line);
} catch (Exception ex) {
return -1;
}
}
public long getLong() {
try {
String line = reader.readLine();
return Long.parseLong(line);
} catch (Exception ex) {
return -1;
}
}
public short getShort() {
try {
String line = reader.readLine();
return Short.parseShort(line);
} catch (Exception ex) {
return -1;
}
}
public String getString() {
try {
String line = reader.readLine();
return line;
} catch (Exception ex) {
return " ";
}
}
public char getChar() {
try {
return (char) reader.read();
} catch (Exception ex) {
return (' ');
}
}
public void close() {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
The standard way for user input is to use a Scanner which already contains methods for reading different kinds of input.
You're not supposed to close the reader, because that will then close System.in which is not what you want.
By calling reader.close(); you are not only closing the reader himself because the call invokes the close() method of the InputStreamReader aswell and therefore closes System.in (which you can not reopen).
A possible Solution would be to use a Scanner as Kayaman pointed out in his answer or to override the close() method like this:
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in){#Override public void close(){});
I want to search for particular string inside all files in a Directory.
Ex: Search for "tiger" in path D:/test/chapters/
D:/test/chapters
/chapter1.log
/chapter2.log
/chapter3.log all these sub files under D:/test/chapters/ .
Sample code I have tried :
public class Example {
public Example() {
super();
}
public int plugin_execute() {
boolean foundstring=false;
try {
File dir = new File("D:/test/chapters");
String[] children = dir.list();
if (children == null) {
System.out.println("does not exist is not a directory");
} else {
for (int i = 0; i < children.length; i++) {
String filename = children[i];
System.out.println(filename);
if (filename !=null) {
foundstring = testString(filename, "tiger");
System.out.println("failed");
}
//Search for entry in file
if (!foundstring) {
return //failuremsg
} else {
System.out.println("failed");
return //succes
}
}
}
return 1;
} catch (Exception e) {
return //error mssg
}
}
private boolean teststring(String filePath, String str) {
BufferedReader br = null;
File file = new File(filePath);
boolean result = false;
if(!file.exists())
return false;
try {
br = new BufferedReader(new FileReader(filePath));
String sCurrentLine;
while ((sCurrentLine = br.readLine()) != null) {
if (sCurrentLine.contains(str)) {
result = true;
System.out.println(str);
System.out.println("Found entry ");
break;
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
}
}
It only returns the output of last file, means if it search success in last file it return success otherwise failed.
But I want success if string is found in first file. i.e chapter1 should return success, if not found in Chapter1 it should continue search in chapter2 ....
Please suggest how can I modify this code..
Problem: Simple mix-up with ! and true/false locations.
Solution: Change this
if (! foundString)
{
return // failuremsg
}
else
{
System.out.println("failed");
return // success
}
to
if (foundString)
{
// return success message
}
else
{
// return failure message
}
Another problem I believe I see in your code is that the line foundstring = findString(filename, "tiger"); calls the method findString, whereas the other method you posted in your code is testString. I assume this is a name mix up.
public void listFiles(Path dir , String text)
{
try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(dir))
{
for (Path path : directoryStream)
{
if (Files.isRegularFile(path) && Files.isReadable(path))
{
//this.findString(path, text);
}
}
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
private boolean findString(Path file, String text)
{
//Your implementation
return true;
}
I'm new here, and I got a problem when I'm trying to read a file.
Here is my code
public void openFile()
{
try
{
if(Board.state == Board.STATE.LEVEL1)
{
scan = new Scanner(new File("D://OOP Photos//Map.txt"));
}
}
catch(FileNotFoundException e)
{
e.printStackTrace();
}
try
{
if(Board.state == Board.STATE.LEVEL2)
{
scan = new Scanner(new File("D://OOP Photos//Map1.txt"));
}
}
catch(Exception e)
{
System.out.println("Error loading MAP !!! ");
}
try
{
if(Board.state == Board.STATE.LEVEL3)
{
scan = new Scanner(new File("D://OOP Photos//Map2.txt"));
}
}
catch(Exception e)
{
System.out.println("Error loading MAP !!! ");
}
}
If I comment out the if statement it is okay, but if I leave it there, it will throw a NullPointerException in the next method:
public void readFile()
{
while(scan.hasNext())
{
for(int i = 0; i < 10; i++)
{
if(scan.hasNext())
{
Map[i] = scan.next();
}
}
}
}
Can you help me ?
Thank You :)
Do something like this:
public static void main(String args[]) {
String filename;
if(Board.state == Board.STATE.LEVEL1) {
filename = "D://OOP Photos//Map1.txt";
}
else if (Board.state == Board.STATE.LEVEL2) {
filename = "D://OOP Photos//Map2.txt";
}
else if (Board.state == Board.STATE.LEVEL3) {
filename = "D://OOP Photos//Map3.txt";
}
readFile(filename);
}
public void readFile(String filename) {
try {
Scanner scan = new Scanner(new File(filename));
int i = 0;
while(scan.hasNext()) {
Map[i] = scan.next();
i++;
}
}
catch(FileNotFoundException e) {
System.out.println("Error loading MAP !!! ");
}
}
Before each IF statement simply print out the values of Board.state and Board.STATE.LEVELx? That will tell you exactly why your IFs are all false. Or just set a breakpoint and inspect the values.
Also try changing your == in the IFs to .equals().
Your app logic makes me confused. Why not jsut make simple public Scanner openFile(String filePath) method, with one try / catch block, with one Scanner scan = new Scanner(new File(filePath))?
Here's something to consider:
public static class Board {
// I'm assuming this is what's happening?
public static State state = State.LEVEL1;
public enum State {
LEVEL1("Map.txt"), LEVEL2("Map1.txt"), LEVEL3("Map2.txt");
private final String fileName;
private State(String fileName) {
this.fileName = fileName;
}
public String getFileName() {
return fileName;
}
}
};
public void openFile() {
if (Board.state == null)
throw new RuntimeException("board state not set");
File file = new File("D:/OOP Photos/", Board.state.getFileName());
try (Scanner scan = new Scanner(file)) {
// do the scanning
} catch (FileNotFoundException fnfe) {
// handle file not found
} catch (Exception e) {
// handle other errors
}
}
date time kg
12/10/2013 00.00.01 1
13/11/2013 00.00.05 2
17/12/2013 00.00.90 5
21/12/2013 00.00.23 6
27/12/2013 00.00.43 9
I have these data in an txt file. I would like to make o program in java that would read these data. I ' ve written the code above but I have mistakes. Could someone help me? The data have space between each other.
import java.io*;
public class ReadTextfile{
public static void main (String[] args) {
File file = new File ("test.txt");
StringBuilder line = new StringBuilder();
BufferedReader reader = null;
try {
reader = new BufferedReader (new FileReader(file));
String text = null;
while ((text = reader.readLine()) !=null) {
line.append(text)
.append(System.getProperty ("line.separator"));
}
}
catch (IOException e) {
e.printStackTrace();
catch (FileNotFoundException e) {
e.printStackTrace();
}finally {
try {
if (reader !=null){
reader.close();
}
}
catch (IOException e) {
e.printStackTrace();
}
}
System.out.println(line.toString());
}
}
boy you are only having some syntax problem
1 : replace
import java.io* with import java.io.*
2 : take care of your catch body being started and closed properly
try
{
// your code
}
catch(Exception e)
{
}
here is the working code , compare your program
import java.io.*;
public class ReadTextfile{
public static void main (String[] args)
{
File file = new File ("C:/Users/hussain.a/Desktop/test.txt");
StringBuilder line = new StringBuilder();
BufferedReader reader = null;
try {
reader = new BufferedReader (new FileReader(file));
String text = null;
while ((text = reader.readLine()) !=null) {
line.append(text)
.append(System.getProperty ("line.separator"));
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
try {
if (reader !=null){
reader.close();
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
System.out.println(line.toString());
}
}
catch (FileNotFoundException e)
This is unreachable code, since above it you caught IOException.
Note that:
public class FileNotFoundException extends IOException
Your code won't compile. Remove this catch (You didn't even close it..)
Another thing, if this is not a type, you should replace java.io* with import java.io.*.
I would take the following approach:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class ReadTextFile
{
public static void main(String[] args) throws FileNotFoundException
{
File file = new File("test.txt");
Scanner scanner = new Scanner(file);
List<Result> results = new ArrayList<Result>();
while(scanner.hasNextLine())
{
String currentLine = scanner.nextLine();
String [] resultArray = currentLine.split(" ");
results.add(new Result(resultArray[0], resultArray[1], resultArray[2]));
}
scanner.close();
}
private static class Result
{
private String date;
private String time;
private String kg;
public Result(String date, String time, String kg)
{
super();
this.date = date;
this.time = time;
this.kg = kg;
}
public String getDate()
{
return date;
}
public String getTime()
{
return time;
}
public String getKg()
{
return kg;
}
}
}
Now you can pull out any information that you want to from the list of results that you have.
So if you wanted to print everything, you could do the following:
for(Result singleResult : results)
{
System.out.println(singleResult.getDate() + " " + singleResult.getTime() + " " + singleResult.getKg());
}
You basically can do whatever you want to with the data. This approach would also allow you to transform the data into different types before you even create the Result object.
I'm running a device with busybox.
Folder or files with no whitespaces moved correctly, but seems that folders with whitespaces don't move correctly
public static boolean mv(File source, File target) {
if (!source.exists() || !target.exists()) {
return false;
}
try {
StringBuilder command = new StringBuilder("mv -v ");
command.append('\"');
command.append(source.getCanonicalPath());
command.append('\"');
command.append(' ');
command.append('\"');
command.append(target.getCanonicalPath());
command.append('\"');
System.out.println(command.toString());
Process process = Runtime.getRuntime().exec(command.toString());
StringBuilder output = new StringBuilder();
BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
output.append(line);
}
System.out.println(output.toString());
return process.waitFor() == 0;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
The output is
mv -v "/storage/sdcard0/media/music/Progressive Death Metal" "/storage/sdcard0/Music"
No mv output, method just returns "false" (non-zero exit code).
And must I use canonical path, or is it okay to use absolute path and leave it to shell?
EDIT
I also came up that if the filename had quotes, the argument will be wrong, so I made a method adding escape characters
private static String getCommandLineString(String input) {
return input.replace("\\", "\\\\")
.replace("\"", "\\\"")
.replace("\'", "\\\'")
.replace("`", "\\`")
.replace(" ", "\\ ");
}
And now mv looks like this
public static boolean mv(File source, File target) {
if (!source.exists() || !target.exists()) {
return false;
}
try {
StringBuilder command = new StringBuilder("mv -v ");
command.append(getCommandLineString(source.getAbsolutePath()));
command.append(' ');
command.append(getCommandLineString(target.getAbsolutePath()));
System.out.println(command.toString());
Process process = Runtime.getRuntime().exec(command.toString());
StringBuilder output = new StringBuilder();
BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
output.append(line);
}
System.out.println(output.toString());
return process.waitFor() == 0;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
what I get is
mv -v /sdcard/media/music/Progressive\ Death\ Metal /sdcard/Music
But still I get silent non-zero exit code.
Finally got it working. Exec should ask for shell, while OutputStream should write commands.
private static boolean execute(boolean superuser, String command) {
DataOutputStream os = null;
try {
Process process = Runtime.getRuntime().exec(superuser ? "su" : "sh");
os = new DataOutputStream(process.getOutputStream());
os.writeBytes(command + "\n");
os.flush();
os.writeBytes("exit\n");
os.flush();
return process.waitFor() == 0;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (os != null) { try { os.close(); } catch (Exception e) {} }
}
return false;
}
public static boolean mv(File source, File target) {
if (!source.exists() || !target.exists()) {
return false;
}
try {
StringBuilder command = new StringBuilder("mv ");
command.append(getCommandLineString(source.getAbsolutePath()));
command.append(' ');
command.append(getCommandLineString(target.getAbsolutePath()));
return execute(false, command.toString());
} catch (Exception e) {
e.printStackTrace();
return false;
}
}