Java, reading the file from input.txt has an issue - java

I am working on the project. For my purpose, I need to use them that find the median of medians.
At my point, I need to see the read
I also created the input.txt like that below
3 7
1 4 5 7 9 11 13
Below the snippet, I created the variable for the readpath.
// need the variable of filename to read
private static final String INPUT_FILE_PATH = "input.txt";
So, then I appended the code that needs to read the numerical integers in the input.txt in the main function as known below
public static void main(String args[]){
// read the input file
// TODO need to fix this readpath that gets the bad input
// ! ASAP
Path inputPath = Paths.get(INPUT_FILE_PATH);
Charset charset = Charset.forName("UTF-8");
List<String> fileLines = new ArrayList<>(0);
try {
fileLines = Files.readAllLines(inputPath, charset);
} catch (IOException ex) {
System.err.println("Error reading file: " + ex.getMessage());
System.exit(1);
}
int read_line = 0;
try {
read_line = Integer.parseInt(fileLines.get(0));
} catch (NumberFormatException ex) {
System.err.println("bad file input");
System.exit(1);
}
System.out.println("reading... " + read_line);
// end of reading the filename operation
}
As a result, this code suppose to work. I get the output that is bad file input. I do not understand why it gets bad file. By the way, I put all files together in the same directory.

int read_line = 0;
int read_line2 = 0;
try {
String[] words = fileLines.get(0).split("\\s+"); // Split on whitespace.
read_line = Integer.parseInt(words[0]);
read_line2 = Integer.parseInt(words[1]);
} catch (NumberFormatException ex) {
System.err.println("bad file input - not a number; " + e.getMessage());
System.exit(1);
}
The line contains two numbers, and results in a NumberFormatException.

Related

While reading a CSV I get a question mark at the beginning

I'm trying to do a small school practice about Java Text I/O and while trying to read a CSV file with name prefixes (a Dutch thing) and surnames I got a question mark in the beginning.
It's a small exercise where I need to add my code to an already existing project with 3 small files to practice the use of Text I/O, see project code: https://github.com/Remzi1993/klantenBestand
public void vulNamenLijst() {
// TODO: Lees het bestand "resources/NamenlijstGroot.csv" en zet elke regel (<tussenvoegsel>,<achternaam>)
// in de ArrayList namenLijst.
file = new File("resources/NamenlijstGroot.csv");
try (
Scanner scanner = new Scanner(file);
) {
while (scanner.hasNext()) {
String line = scanner.nextLine();
String[] values = line.split(",");
String namePrefix = values[0];
String surname = values[1];
namenLijst.add(namePrefix + " " + surname);
}
} catch (FileNotFoundException e) {
System.err.println("Data file doesn't exist!");
} catch (Exception e) {
System.err.println("Something went wrong");
e.printStackTrace();
}
}
I'm sorry for the use of Dutch and English at the same time in the code. I try to write my own code in English, but this code exercise already existed and I only needed to add some code with the //TODO to practice Text I/O.
This is what I get:
My CSV file:
#funky is correct. Your file starts with a UTF8-BOM.
output of xxd:
00000000: efbb bf64 652c 4a6f 6e67 0a2c 4a61 6e73 ...de,Jong.,Jans
00000010: 656e 0a64 652c 5672 6965 730a 7661 6e20 en.de,Vries.van
The first three bytes are: ef bb bf
To mitigate the BOM using a 'standard' component, you can use Apache's BOMInputStream. Note that BOMs come in multiple flavours (see here for more details), and this should handle them all reliably.
If you have a sizeable project, you may find you have the BOMInputStream in your project already via commons-io
Scanner will take an input stream (see here)
I found an easy solution:
final String UTF8_BOM = "\uFEFF";
if (line.startsWith(UTF8_BOM)) {
line = line.substring(1);
}
A simple workable example:
File file = new File("resources/NamenlijstGroot.csv");
try (
Scanner scanner = new Scanner(file, StandardCharsets.UTF_8);
) {
while (scanner.hasNext()) {
String line = scanner.nextLine().strip();
final String UTF8_BOM = "\uFEFF";
if (line.startsWith(UTF8_BOM)) {
line = line.substring(1);
}
String[] values = line.split(",");
String namePrefix = values[0];
String surname = values[1];
namenLijst.add(namePrefix + " " + surname);
}
} catch (FileNotFoundException e) {
System.err.println("Data file doesn't exist!");
} catch (Exception e) {
System.err.println("Something went wrong");
e.printStackTrace();
}

Java BufferedReader acting strange

I can't understand for the life of me why bufferedreader is not reading the next line in my file. It keeps returning an empty string. I put the reader in a while loop in the proper format. My text file does not contain any special characters. It only contains numbers and some strings delimited by white spaces. I don't get it.
//Read from file method
public void readFile(File x) throws IOException{
File rFile = x;
String fileLine;
Transaction holder;
int Type;
//This will destroy the current account to add in the new one
//Main.$acct.destroyTrans();
try {
// FileReader reads text files in the default encoding.
FileReader fileReader = new FileReader(rFile);
// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader = new BufferedReader(fileReader);
//Gathering initial information about account
Main.$acct.setName(bufferedReader.readLine());
Main.$acct.setBalance(Double.parseDouble(bufferedReader.readLine()));
Main.$acct.setTransCount(Integer.parseInt(bufferedReader.readLine()));
Main.$acct.setSC(Double.parseDouble(bufferedReader.readLine()));
//Adding the objects
while((fileLine = bufferedReader.readLine()) != null) {
//Tokenize the String to extract information
StringTokenizer st = new StringTokenizer(fileLine," ");
//Go through each token and put it into an arrayList
ArrayList<String> list = new ArrayList();
while(st.hasMoreTokens()) {
list.add(st.nextToken());
}
//Grab each piece of data
Type = Integer.parseInt(list.get(0));
//Route the proper objects to their proper places
switch(Type){
case 1:
{
holder = new Check(Integer.parseInt(list.get(1)), Type, Double.parseDouble(list.get(3)), Integer.parseInt(list.get(2)));
Main.$acct.addNewTrans(holder);
break;
}
case 2:
{
holder = new Deposit(Integer.parseInt(list.get(1)), Type, Double.parseDouble(list.get(5)), Double.parseDouble(list.get(3)),
Double.parseDouble(list.get(4)));
Main.$acct.addNewTrans(holder);
break;
}
case 3:
{
holder = new Transaction(Integer.parseInt(list.get(1)), Type, Double.parseDouble(list.get(4)));
Main.$acct.addNewTrans(holder);
break;
}
default:
{}
}
//End of switch
}
//End of while loop
bufferedReader.close();
}
//End of Try
//Exception handling portion
catch(FileNotFoundException ex) {
System.out.println(
"Unable to open file '" +
rFile.getName() + "'");
}
catch(IOException ex) {
System.out.println(
"Error reading file '"
+ rFile.getName() + "'");
// Or we could just do this:
// ex.printStackTrace();
}
}
Sample File:
billy
500
4
5
1 0 1 100
3 1 Srv. Chrg. 0.15
2 2 Deposit 100 100 200
Your code is running just fine as long as the input file format and encoding are the standard ones.
Make sure your input file has no redundant line breaks (or an extra line break at the end of the file);
I tested your code with ANSI encoded file, and it worked as expected.
Fix your exception handling to handle general cases - it will help you debug the error.
i.e. do something like this at the end of the method:
} catch(Exception e) {
// Throw the exception here, or print it to the console...
e.printStackTrace();
}
Goodluck!

Java doesn't display accent words correctly

I have a java program that saves a text file and then outputs it contents in a dialog.
When I run the program inside my IDE (BlueJ) the display is as follows:
As you can see in the dialog the line "1º) Mónica" appears correctly.
But when I run the same program outside the IDE the "Mónica" doesn't appear right, as you can see in the picture:
How can I fix this to always display the right output?
this is the code that reads the text file to a string
public String recordesString()
{
Premios premios = new Premios();
File recordes = new File("recordes.txt");
if(!recordes.exists()) {
if(!client.isConnected())
openFTPSession();
downloadRecordes(); // this downloads the recordes.txt file
}
Scanner s = null;
try {
s = new Scanner(recordes);
} catch (Exception e) {
e.printStackTrace();
}
String string = "";
String linha = null;
for(int i = 1; s.hasNext(); i++) {
linha = s.nextLine();
String palavra[] = linha.split(" ",2);
string += i+"º) "+palavra[1] +" "+ premios.getPremio(Integer.parseInt(palavra[0]))+"\n";
}
s.close();
try {
Files.deleteIfExists(Paths.get(ficRecordes));
} catch (Exception e) {
e.printStackTrace();
}
return string;
}
Scanner reads the file using the underlying platform's default charset.
See http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#Scanner(java.io.File)
I'd expect the file is encoded in UTF-8 and when you run outside the IDE, the default charset is ISO-latin-1 or so. If you specify the file's encoding when creating the scanner, the results will be predictable.
s = new Scanner(recordes, "UTF-8");

program only read last line in .txt file java

I have a problem and don't know what to do. This method is supposed to read all the text in a .txt document. My problem is when the document contains more then one line of text and the program only read the last line. The program don't need to worry about signs like . , : or spaces, but it have to read all the letters. Can anybody help me?
example text
hello my name is
(returns the right result)
hello my
name is
(returns only name is)
private Scanner x;
String readFile(String fileName)
{
try {
x = new Scanner (new File(fileName + (".txt")));
}
catch (Exception e) {
System.out.println("cant open file");
}
while (x.hasNext()) {
read = x.next();
}
return read;
}
It's because when you use read = x.next(), the string in the read object is always being replaced by the text in the next line of the file. Use read += x.next() or read = read.concat(x.next()); instead.
You replace every read with every read(). Also, you didn't close() your Scanner. I would use a try-with-resources and something like,
String readFile(String fileName)
{
String read = "";
try (Scanner x = new Scanner (new File(fileName + (".txt")));) {
while (x.hasNextLine()) {
read += x.nextLine() + System.lineSeparator(); // <-- +=
}
} catch (Exception e) {
System.out.println("cant open file");
}
return read;
}

FileNotFoundException catch error when reading from file in Java

I am trying to write a simple program that reads integers in from a text file and then outputs the sum to an output file. The only error I am getting is in my catch block at line 38 "Unresolved compilation problem: file cannot be resolved". Note that "file" is the name of my input file object. If I comment out this exception block, the program runs fine. Any advice would be appreciated!
import java.io.*;
import java.util.Scanner;
public class ReadWriteTextFileExample
{
public static void main(String[] args)
{
int num, sum = 0;
try
{
//Create a File object from input1.txt
File file = new File("input1.txt");
Scanner input = new Scanner(file);
while(input.hasNext())
{
//read one integer from input1.txt
num = input.nextInt();
sum += num;
}
input.close();
//create a text file object which you will write the output to
File output1 = new File("output1.txt");
//check whether the file's name already exists in the current directory
if(output1.exists())
{
System.out.println("File already exists");
System.exit(0);
}
PrintWriter pw = new PrintWriter(output1);
pw.println("The sum is " + sum);
pw.close();
}
catch(FileNotFoundException exception)
{
System.out.println("The file " + file.getPath() + " was not found.");
}
catch(IOException exception)
{
System.out.println(exception);
}
}//end main method
}//end ReadWriteTextFileExample
The file variable is declared within the try block. It's out of scope in the catch block. (Although it couldn't happen in this case, imagine if the exception were thrown before execution had even reached the variable declaration. Basically, you can't access a variable in a catch block which is declared in the corresponding try block.)
You should declare it before the try block instead:
File file = new File("input1.txt");
try
{
...
}
catch(FileNotFoundException exception)
{
System.out.println("The file " + file.getPath() + " was not found.");
}
catch(IOException exception)
{
System.out.println(exception);
}
Scope in Java is based on blocks. Any variable you declare inside a block is only in scope until the end of that same block.
try
{ // start try block
File file = ...;
} // end try block
catch (...)
{ // start catch block
// file is out of scope!
} // end catch block
However, if you declare file before your try block, it will remain in scope:
File file = ...;
try
{ // start try block
} // end try block
catch (...)
{ // start catch block
// file is in scope!
} // end catch block

Categories