I got a problem when I'm trying to read int from text file.
I'm using this kind of code
import java.util.Scanner;
import java.io.*;
File fileName =new File( "D:\\input.txt");
try {
Scanner in = new Scanner(fileName);
c = in.nextInt();
n = in.nextInt();
} catch(Exception e){
System.out.println("File not Found!!!");
}
If my text is edit like this
30
40
So it will work (meaning c=30, n=40).
But if I want to edit the text file that will be like this
c=30
n=40
My code will not work.
How can I change my code to read only the numbers and ignore the "c=" and n="
or any others chars besides the numbers?
You need to read your lines using Scanner.nextLine, split each line on =, and then convert the 2nd part to integer.
Remember to do the check - Scanner.hasNextLine before you read any line. So, you need to use a while loop to read each line.
A Simple implementation, you can extend it according to your need: -
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String[] tokens = line.split("=");
try {
System.out.println(Integer.parseInt(tokens[1]);
} catch (NumberFormatException e) {
e.printStackTrace();
}
}
Now if you want to use those numbers later on, you can also add them in an ArrayList<Integer>.
Following the format you want to use in the input file then it would be better if you make use of java.util.Properties. You won't need to care about the parsing.
Properties props = new Properties();
props.load(new FileInputStream(new File("D:\\input.txt")));
c = Integer.parseInt(props.getProperty("c"));
n = Integer.parseInt(props.getProperty("n"));
You can read more about the simple line-oriented format.
you could read line by line(Scanner.nextLine) and check every character in the line by asking isDigit()
If your data line will always be in the same format x=12345, use a regex to get the numeric value from the line
Related
I'm trying to read data from a file that contains integers, but the Scanner doesn't read anything from that file.
I've tried to read the file from the Scanner :
// switch() blablabla
case POPULATION:
try {
while (sc.hasNextInt()) {
this.listePops.add(sc.nextInt());
}
} catch (Exception e) {
System.err.println("~ERREUR~ : " + e.getMessage());
}
break;
And if I try to print each sc.nextInt() to the console, it just prints a blank line and then stops.
Now when I read the same file as a String:
?652432
531345
335975
164308
141220
1094283
328278
270582
// (Rest of the data)
So, I guess it can't read the file as a list of integers since there's a question mark at the beginning, but the problem is that this question mark doesn't appear anywhere in my file, so I can't remove it. What am I supposed to do?
If the first character in the file is a question mark (?) and its original origin is unknown then it is usually the UTF-8 Byte Order Mark (BOM). This means the file was saved as UTF-8. The Microsoft Notepad application will add a BOM to the saved text file if that file was saved in UTF-8 instead of ANSI. There are also other BOM characters for UTF-16, UTF-32, etc.
Reading a text file as String doesn't look like a bad idea now. Changing the save format of the file can work to but that BOM may have actual intended purpose for another application, so, that may not be a viable option. Let's read the file as String lines (read comments in code):
// Variable to hold the value of the UTF-8 BOM:
final String UTF8_BOM = "\uFEFF";
// List to hold the Integer numbers in file.
List<Integer> listePops = new ArrayList<>();
// 'Try With Resources' used to to auto-close file and free resources.
try (Scanner reader = new Scanner(new File("data.txt"))) {
String line;
int lineCount = 0;
while (reader.hasNextLine()) {
line = reader.nextLine();
line = line.trim();
// Skip blank lines (if any):
if (line.isEmpty()) {
continue;
}
lineCount++;
/* Is this the first line and is there a BOM at the
start of this line? If so, then remove it. */
if (lineCount == 1 && line.startsWith(UTF8_BOM)) {
line = line.substring(1);
}
// Validate Line Data:
// Is the line a String representation of an Integer Number?
if (line.matches("\\d+")) {
// Yes... then convert that line to Integer and add it to the List.
listePops.add(Integer.parseInt(line));
}
// Move onto next file line...
}
}
catch (FileNotFoundException ex) {
// Do what you want with this exception (but don't ignore it):
System.err.println(ex.getMessage());
}
// Display the gathered List contents:
for (Integer ints : listePops) {
System.out.println(ints);
}
I want to read only the parts i need to. For example my text file look likes these
Name Age Gender
=====================
Donald 13 Male
John 14 Non-binary
Pooh 42 Female
I only want to read the data but i don't know how because my code reads a .txt file line by line
try {
File myObj = new File("database.txt");
Scanner myReader = new Scanner(myObj);
while (myReader.hasNextLine()) { //to read each line of the file
String data = myReader.nextLine();
String [] array = data.split(" "); //store the words in the file line by line
if(array.length ==5){ // to check if data has all five parameter
people.add(new Person(array[0], array[1],array[2], Double.parseDouble(array[3]), Double.parseDouble(array[4])));
}
}
JOptionPane.showMessageDialog(null, "Successfully Read File","Javank",JOptionPane.INFORMATION_MESSAGE);
myReader.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
You can simply call myReader.nextLine() twice before entering your loop to ignore the first two lines.
Another approach you can take is to use a RandomAccessFile object instead of a Scanner to process your input. If you know how many characters are in the file before the beginning of your relevant data, you can use the RandomAccessFile object's seek method to skip to the beginning of your input, e.g. if there are 50 characters in the file before your data you can use randomAccessFile.seek(50) and then read the lines with randomAccessFile.readLine().
I would probably recommend using the first method of skipping 2 lines however because it seems more simple and robust.
I'm trying to split each line from a text file into cells in an Array. Can I do it with split function and not count the lines in order to create an array?
I am using Scanner for reading files from Scanner. The file contains in each line the following format: number_number
I want to save number_number as a string into a cell in Array.
However, I don't know how many lines in my text file could be, in order to set an array size. I dont want to useLinkedList`, please use the assumption that will not have many lines.
Is it possible to read from file and save each line into cell in array?
There is no problem to change the method from Scanner to another one.
The problem in my code currently that it saves only the first line in my file.
public String[] readFromFileToStringArray(String s) {
Scanner scanner = null;
try {
scanner = new Scanner(new File(s));
} catch (IOException e) {
e.printStackTrace();
}
String[] fileText = null;
if (scanner != null)
while (scanner.hasNext())
fileText = scanner.nextLine().split("\n");
return fileText;
}
When using scanner.nextLine() you read the text until the \n character, so the split you did is pointless since the line string won't have this character.
You can read all the file and then split it:
public String[] readFromFileToStringArray(String s) {
String text = new String(Files.readAllBytes(Paths.get(s)),
StandardCharsets.UTF_8);
return text.split("\n");
}
But really as the other answered said, it would probably be better to simply use List
Should you change the way to add string to the array?
fileText.add(scanner.nextLine());
OR:
List<String> list = new ArrayList<String>(Arrays.asList(fileText));
list.addAll(Arrays.asList(scanner.nextLine().splite("\n")));
String[] fileText = list.toArray();
List<String> lines = Files.readAllLines(pathToFile);
java Files is the easiest way for this.
First off let me start by saying that I know I'm not the only one who has experienced this issue and I spent the last couple of hours to research how to fix it. Sadly, I can't get my scanner to work. I'm new to java so I don't understand more complicated explanations that some answers have in different questions.
Here is a rundown:
I'm trying to read out of a file which contains escape characters of cards. Here is a short version: (Numbers 2 and 3 of 4 different card faces)
\u26602,2
\u26652,2
\u26662,2
\u26632,2
\u26603,3
\u26653,3
\u26663,3
\u26633,3
This is the format: (suit)(face),(value). an example:
\u2663 = suit
3 = face
3 = value
This is the code I'm using for reading it:
File file = new File("Cards.txt");
try {
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String[] temp = line.split(",");
cards.add(new Card(temp[0], Integer.parseInt(temp[1])));
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
the ArrayList cards should have 52 cards after this containing a name (suit and face) and a value. When i try to print the name this is the output:
\u26633
While it should be:
♣3
Can anyone give me pointers towards a solution? I really need this issue resolved. I don't want you to write my code for me.
Thanks in advance
Simply store directly the suit characters into your files Cards.txt using UTF-8 as character encoding instead of the corresponding unicode character format that is only understood by java such that when it is read from your file it is read as the String "\u2660" not as the corresponding unicode character.
Its content would then be something like:
♠2,2
...
Another way could be to use StringEscapeUtils.unescapeJava(String input) to unescape your unicode character.
The code change would then be:
cards.add(new Card(StringEscapeUtils.unescapeJava(temp[0]), Integer.parseInt(temp[1])));
You'll have to save your file with UTF-8 encoding and then read the file using the same encoding.
♥,1
♥,2
♥,3
Here is the code snippet:
BufferedReader buff = new BufferedReader(new InputStreamReader(
new FileInputStream("Cards.txt"), "UTF-8"));
String input = null;
while (null != (input = buff.readLine())) {
System.out.println(input);
String[] temp = input.split(",");
cards.add(new Card(temp[0], Integer.parseInt(temp[1])));
}
buff.close();
Also, you need to make sure that your console is enabled to support UTF-8. Look at this answer to read more about it.
so i have a text file that consist:
not voting/1/harold/18
not voting/2/isabel/24
this describes like not voting/number for vote/name/age. my goal is to edit not voting to voted but still keeping the other info (number for vote/name/age). the user will input the number for vote then if it exist, the not voting will automatically change to voted
here is my code:
File original = new File("C:\\voters.txt");
File temporary = new File("C:\\tempvoters.txt");
BufferedReader infile = new BufferedReader(new FileReader(original));
PrintWriter outfile = new PrintWriter(new PrintWriter(temporary));
numberforvote=JOptionPane.showInputDialog("Enter voters number: ");
String line=null;
while((line=infile.readLine())!=null){
String [] info=line.split("/");
if(info[1].matches(numberforvote)){
all="VOTED"+"/"+info[1]+"/"+info[2]+"/"+info[3]+"/"+info[4]+"/"+info[5]+"/"+info[6]+"/"+info[7]+"/"+info[8]+"/"+info[9]+"/"+info[10]+"/"+info[11]+"/"+info[12];
outfile.println(all);
outfile.flush();
}
}
infile.close();
outfile.close();
original.delete();
temporary.renameTo(original);
this works but the problem with my code is the second line (not voting/2/isabel/24) will disappear/deleted. i want everything to be the same except for the not voting in the given/entered number for vote.
Your output file gets entirely overwritten , so you have to write all lines, even those that you didn't intend to modify :
if(info[1].matches(numberforvote)){
all="VOTED"+"/"+info[1]+"/"+info[2]+"/"+info[3]+"/"+info[4]+"/"+info[5]+"/"+info[6]+"/"+info[7]+"/"+info[8]+"/"+info[9]+"/"+info[10]+"/"+info[11]+"/"+info[12];
outfile.println(all);
}
else{
outfile.println(line); // this will write the "unchanged" lines
}
outfile.flush();
if(info[1].matches(numberforvote)){
all="VOTED"+"/"+info[1]+"/"...;
outfile.println(all);
outfile.flush();
} else {
outfile.println( line );
}
Copy to output if there's no match.
I should add that using a regex for a single string compare should be reduced to the simpler info[1].equals(numberforvote). But calling numberforvote = numberforvote.trim(); could be useful.
Move it outside the if and only change the part you need to change. That way you can change whatever you want then rebuild the line.
if(info[1].matches(numberforvote)){
into[0] = VOTED;
}
all=info[0]+"/"+info[1]+"/"+info[2]+"/"+info[3]+"/"+info[4]+"/"+info[5]+"/"+info[6]+"/"+info[7]+"/"+info[8]+"/"+info[9]+"/"+info[10]+"/"+info[11]+"/"+info[12];
outfile.println(all);
outfile.flush();
or clean up that ugly line
StringBuilder sb = new StringBuilder();
for (String element : info){
sb.append(element);
}
outfile.println(sb.toString());
Other Answers
You could just output the unchanged line like others have suggested
outfile.println(line);
but it's not as flexable if you want to make other changes later.
You should simplify the split and writing to:
String [] info=line.split("/",2);
if ( info.length == 2 ) {
...
outfile.println("VOTED/"+info[1]);
} else {
// input error
}