Reading from a file in Java - java

I wrote a program that reads from a text file using Java. The file has 1 column with a lot of integer values and each value is being added to an array list. However, when I print the array list, between each number I am getting an empty entry. For example if in text file I have:
4
55
I am getting:
1 : ÿþ4 (Also I do not know what this weird character is)
2 :
3 : 555
Code:
import java.io.*;
import java.util.Scanner;
import java.util.ArrayList;
public class ReadFile {
public static void main(String[] args) {
try
{
Scanner input = new Scanner("ReadingFile.txt");
File file = new File(input.nextLine());
input = new Scanner(file);
ArrayList numbers = new ArrayList();
int i=1;
while (input.hasNextLine()) {
String line = input.nextLine();;
numbers.add(line);
System.out.println(i + " : " + line);
i++;
}
input.close();
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
}
I tried to avoid using the arraylist and just do :
System.out.println(i + " " + line);
however this problem is still there so I am guessing that it is not an ArrayList problem.

Provided your text file is actually a good text file, it could be a character encoding thing. You need to provide the correct character set to your scanner in its constructor. So change the line:
input = new Scanner(file);
Into something like:
String charset = "UTF-8";
input = new Scanner(file, charset);
Ofcourse, you need to figure out which character set your file is actually stored as and use that one. I do UTF-8 here only as an example.

OK, the problem is that you're actually reading binary from an excel file, hence the strange characters. If you want to read an excel file directly, then use a library such as JXL (http://jexcelapi.sourceforge.net/) - here's a good tutorial for using that API: http://www.vogella.com/tutorials/JavaExcel/article.html
Otherwise, you would want to save export your excel file to CSV format and read the file with your code.

weird chars should be writeUTF prefix or BOM. so, depends on how you write the file, reading method can be different.
if you write file with DataOutputStream and call writeUTF, then you should read the file with readUTF
if it is a simple text file that was written by a text program, like notepad++, I suggest call trim() function for every line.

Looks like your file is UTF-16. These two characters are the Byte order mark of UTF-16.
You must specify that when constructing your Scanner.
final Scanner scanner = new Scanner(file, "UTF-16");

If you don't have Notepad++ (text editor) download it. Open your generated text file using it.
Do find/Replace and populate the fields and check the settings by looking at the image below. then press Replace All. And then save your file. Your text file will be clean.

Related

java open file xlsx

how do I open the excel file located inside my project?
I would like to press a jbutton and open file1
What would you like to do with it? If you just want to handle the data of the Excel-file, I would export my Excel-file to a csv-file (in Excel 2016: File > Export > Change File Type > CSV (Comma delimited)).
The delimiter used for separating data depends on your system settings (mine is set on semicolon to eliminate annoying situations with commas in the cells).
The advantage of a CSV-file is that you can handle the file as any other text file.
Inside the actionPerformed-method of your JButton, you can open the file using:
try (Scanner sc = new Scanner(new File("my_csv_file.csv"))) {
// do anything you want with the file using the scanner object
// for example, print all data to the screen:
// make sure you import java.util.Scanner, java.io.File and java.io.FileNotFoundException
// and catch a FileNotFoundException or throw it to be handled anywhere else
while (sc.hasNextLine()) {
String data[] = sc.nextLine().split(";");
for (String s : data) {
System.out.print(s + "\t");
}
System.out.println();
}
}

how to write a string which starts with - into csv file?

I am trying to write data to CSV file.
The string value which starts with - is getting converted to #NAME? automatically when i open csv file after writing. e.g. If i write test it displays correctly but when i write -test the value would be #NAME? when i open csv file. It is not a code issue but csv file automatically changes the value which starts with - to error(#NAME?). How can i correct this programmatically. below is the code,
public class FileWriterTest {
public static void main(String[] args) {
BufferedWriter bufferedWriter = null;
File file = new File("test.csv");
try {
bufferedWriter = new BufferedWriter(new FileWriter(file));
List<String> records = getRecords();
for (String record : records) {
bufferedWriter.write(record);
bufferedWriter.newLine();
}
bufferedWriter.flush();
System.out.println("Completed writing data to a file.");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bufferedWriter != null)
bufferedWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static List<String> getRecords() {
List<String> al = new ArrayList<String>();
String s1 = "test";
String s2 = "-test";
al.add(s1);
al.add(s2);
return al;
}
}
Could you please assist?
It's a problem with excel. When you open a CSV file in excel it tries to determine cell type automatically which usually fails. The CSV file is alright the editor is not ;)
You can either right click on the field, select Format Cell and there make it a text file (and you might need to remove the automatically inserted '=' sign). Or you can open the CSV file by going into Data - From Text/CSV and in the wizard select the proper column types.
In the formal CSV standard, you can do this by using quotes (") around the field value. They're a text delimiter (as opposed to other kinds of values, like numeric ones).
It sounds like you're using Excel. You may need to enable " as a text delimiter/indicator.
Update: If you double-click the .csv to open it in Excel, even this doesn't work. You have to open a workbook and then import the CSV data into it. (Pathetic, really...)
I got a relatively old version of Excel (2007), and the following works perfectly:
Put the text between double quotes and preceed it with an equal sign.
I.e., -test becomes ="-test".
You file will therefore look like this:
test1,test2,test3
test4,="-test5",test6
UPDATE
Works in Excel-2010 as well.
As Veselin Davidov mentioned, this will break the csv standard but I don't know whether that's a problem.

Working with UTF-8 characters, Java

My basic code is trying to check files exitence, based on paths, but it can't deal with Unicode Characters:
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
File f = new File(input);
if (f.exists()) {
System.out.println("File is Found, According to java.io");
} else {
System.out.println(f.toString() + " is Not Existed, According to java.io ");
}
Path x = Paths.get(input);
if (Files.exists(x)) {
System.out.println("File is Found, According to java.nio");
} else {
System.out.println(x.toString() + " is Not Existed, According to java.nio");
}
when the input (ie. file path) is in ASCII, the code works fine, but when the input contains UTF-8 chars, the code fails in both :
1- printing the input properly.
2- determining does the file exist (ie. even when the file exists, the code tells that file is not exited)
Example:
input:
c://€.jpg
output:
c:\�.jpg is Not Existed, According to java.io
c:\�.jpg is Not Existed, According to java.nio
I use NetBeans, Java 1.8, maven.
PS: I tried to use:
run with :
-Dfile.encoding=UTF-8
add the followign to project properties :
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
, but nothing happened.
Any help, please?
Precisely, you don't need a file encoding, but an input encoding. Therefore you can specify a charset for your Scanner using the Scanner(InputStream source, String charsetName) constructor:
Scanner scanner = new Scanner(System.in, "UTF-8");

java file reader weird output

I set up a FileReader, and opened a file to read, but it gives me a weird output, that I can't seem to fix:
import java.io.BufferedReader;
import java.io.FileReader;
public class FileReading {
public static void main(String [] args) throws Exception {
FileReader file = new FileReader("/Users/danielpersonius/Desktop/test.rtf");
BufferedReader reader = new BufferedReader(file);
String text = "";
String line = reader.readLine();
while (line != null){
// So here, we want to print until it reaches 'null'
text += line;
line = reader.readLine();
}
System.out.println(text);
}
}
This is my output:
{\rtf1\ansi\ansicpg1252\cocoartf1265\cocoasubrtf200{\fonttbl\f0\fswiss\fcharset0
Helvetica;}{\colortbl;\red255\green255\blue255;}\margl1440\margr1440\vieww10800\viewh8400\viewkind0\pard\tx720\tx1440\tx2160\tx2880\tx3600\tx4320\tx5040\tx5760\tx6480\tx7200\tx7920\tx8640\pardirnatural\f0\fs24
\cf0 TEST}
TEST is what the rtf file says, but how do I get rid of all the other stuff I obviously don't want?
I'm on an IMac with OS X Mavericks
The problem is that your are probably creating your file in TextEdit. TextEdit does not save files as a raw text file. Instead it saves it in a RTF (Rich Text File) format which embeds formating commands. You need to use a text editor that can create an ASCII text file.
For more information on RTF.
Just use the same editor you use to write your code to create your "test.*" file :)
On your test file go to format in the toolbar, then click convert to .txt file for conversion.
This change would get rid of the weird output

how to read a text file using scanner in Java?

This is my code to read a text file. When I run this code, the output keeps saying "File not found.", which is the message of FileNotFoundException. I'm not sure what is the problem in this code.
Apparently this is part of the java. For the whole java file, it requires the user to input something and will create a text file using the input as a name.
After that the user should enter the name of the text file created before again (assume the user enters correctly) and then the program should read the text file.
I have done other parts of my program correctly, but the problem is when i enter the name again, it just can not find the text file, eventhough they are in the same folder.
public static ArrayList<DogShop> readFile()
{
try
{ // The name of the file which we will read from
String filename = "a.txt";
// Prepare to read from the file, using a Scanner object
File file = new File(filename);
Scanner in = new Scanner(file);
ArrayList<DogShop> shops = new ArrayList<DogShop>();
// Read each line until end of file is reached
while (in.hasNextLine())
{
// Read an entire line, which contains all the details for 1 account
String line = in.nextLine();
// Make a Scanner object to break up this line into parts
Scanner lineBreaker = new Scanner(line);
// 1st part is the account number
try
{ int shopNumber = lineBreaker.nextInt();
// 2nd part is the full name of the owner of the account
String owner = lineBreaker.next();
// 3rd part is the amount of money, but this includes the dollar sign
String equityWithDollarSign = lineBreaker.next();
int total = lineBreaker.nextInt();
// Get rid of the dollar sign;
// we use the subtring method from the String class (see the Java API),
// which returns a new string with the first 'n' characters chopped off,
// where 'n' is the parameter that you give it
String equityWithoutDollarSign = equityWithDollarSign.substring(1);
// Convert this balance into a double, we need this because the deposit method
// in the Account class needs a double, not a String
double equity = Double.parseDouble(equityWithoutDollarSign);
// Create an Account belonging to the owner we found in the file
DogShop s = new DogShop(owner);
// Put money into the account according to the amount of money we found in the file
s.getMoney(equity);
s.getDogs(total);
// Put the Account into the ArrayList
shops.add(s);
}
catch (InputMismatchException e)
{
System.out.println("File not found1.");
}
catch (NoSuchElementException e)
{
System.out.println("File not found2");
}
}
}
catch (FileNotFoundException e)
{
System.out.println("File not found");
} // Make an ArrayList to store all the accounts we will make
// Return the ArrayList containing all the accounts we made
return shops;
}
If you are working in some IDE like Eclipse or NetBeans, you should have that a.txt file in the root directory of your project. (and not in the folder where your .class files are built or anywhere else)
If not, you should specify the absolute path to that file.
Edit:
You would put the .txt file in the same place with the .class(usually also the .java file because you compile in the same folder) compiled files if you compile it by hand with javac. This is because it uses the relative path and the path tells the JVM the path where the executable file is located.
If you use some IDE, it will generate the compiled files for you using a Makefile or something similar for Windows and will consider it's default file structure, so he knows that the relative path begins from the root folder of the project.
Well.. Apparently the file does not exist or cannot be found. Try using a full path. You're probably reading from the wrong directory when you don't specify the path, unless a.txt is in your current working directory.
I would recommend loading the file as Resource and converting the input stream into string. This would give you the flexibility to load the file anywhere relative to the classpath
If you give a Scanner object a String, it will read it in as data. That is, "a.txt" does not open up a file called "a.txt". It literally reads in the characters 'a', '.', 't' and so forth.
This is according to Core Java Volume I, section 3.7.3.
If I find a solution to reading the actual paths, I will return and update this answer. The solution this text offers is to use
Scanner in = new Scanner(Paths.get("myfile.txt"));
But I can't get this to work because Path isn't recognized as a variable by the compiler. Perhaps I'm missing an import statement.
This should help you..:
import java.io.*;
import static java.lang.System.*;
/**
* Write a description of class InRead here.
*
* #author (your name)
* #version (a version number or a date)
*/
public class InRead
{
public InRead(String Recipe)
{
find(Recipe);
}
public void find(String Name){
String newRecipe= Name+".txt";
try{
FileReader fr= new FileReader(newRecipe);
BufferedReader br= new BufferedReader(fr);
String str;
while ((str=br.readLine()) != null){
out.println(str + "\n");
}
br.close();
}catch (IOException e){
out.println("File Not Found!");
}
}
}
Just another thing... Instead of System.out.println("Error Message Here"), use System.err.println("Error Message Here"). This will allow you to distinguish the differences between errors and normal code functioning by displaying the errors(i.e. everything inside System.err.println()) in red.
NOTE: It also works when used with System.err.print("Error Message Here")

Categories

Resources