How to load a csv in Java - java

I have a .csv file that I want to load in Java so that afterwards I will be able to work on it as on a normal matrix (array). Here you can see my code:
package MirMir;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Try1 {
public static void main(String[] args) throws FileNotFoundException
{
Scanner scanner = new Scanner(new File("/Users/Madalin/NetBeansProjects/imp fr/src/com/mkyong/util/Tracker.csv"));
scanner.useDelimiter(",");
while (scanner.hasNext())
{
System.out.print(scanner.next() + "|");
}
scanner.close();
}
}
The program runs perfectly without any errors, just the output I get in the end is: "BUILD SUCCESSFUL (total time: 0 seconds)" and that's all, without any data or anything.

Here is another way for this
public class Tracker {
public static void main(String[] args) throws FileNotFoundException, IOException
{
File f =new File("D:/Tracker.csv");
BufferedReader br = new BufferedReader(new FileReader(f));
String s ;
while ((s=br.readLine())!=null)
{
System.out.println(s);
}
br.close();
}
}
Well this might work ;)
P.S. Change the file location

The code is fine. No problem. I tested it on a sample csv file.
There seems to be some problem with your csv file.
Post a sample from your csv.

Related

FileReader in Java not finding the file

I'm trying to read a plain text file but somehow FileReader is not finding my text file. I checked the directory using getAbsolutefile() and /Users/djhanz/IdeaProjects/datalab2/pg174.txt is the exact location of the file. I tried datlab2/pg174.txt and everything I possibly could.
Here is my code
public class Program1 {
public static void main(String[] args) {
System.out.println(new File("pg174.txt").getAbsoluteFile());
Scanner testScanner = new Scanner(new BufferedReader(new FileReader("/Users/djhanz/IdeaProjects/datalab2/pg174.txt")));
while (testScanner.hasNextLine())
{
System.out.println(testScanner.nextLine());
}
}
}
The text file is under the same project directory called datalab.
Can someone please enlighten me?
Use Scanner testScanner = new Scanner(new BufferedReader(new FileReader("/pg174.txt")));
FileReader("/pg174.txt") instead of FileReader("pg174.txt").
package com.example.demo;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Scanner;
public class Program1 {
public static void main(String[] args) throws FileNotFoundException {
System.out.println(new File("pg174.txt").getPath());
System.out.println(new File("pg174.txt").getAbsoluteFile());
System.out.println(new File("pg174.txt").getAbsolutePath());
Scanner testScanner = new Scanner(new BufferedReader(new FileReader("/pg174.txt")));
while (testScanner.hasNextLine()) {
System.out.println(testScanner.nextLine());
}
}
}
Output:

How can I read a file from a path relative of my Main class in Java?

On the same directory of my Main.java file, I have a package/folder named database, and inside the database package I have a file named Data.txt.
This is my code of Main.java, but it is throwing this error:
java: exception java.io.FileNotFoundException
How can I get the file from a relative file? I'm used to web development, and usually something with a . dot like "./folder/file.txt" works.
import java.io.File;
import java.util.Scanner;
import java.io.FileNotFoundException;
public class Main {
public static void main(String[] args) {
readFile();
}
public static void readFile() {
File file = new File("./database/Data.txt");
Scanner scanner = new Scanner(file);
try {
while (scanner.hasNextLine()) {
int i = scanner.nextInt();
System.out.println(i);
}
scanner.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
You are not importing FileNotFoundException class. also, scanner statement throws the exception which should inside try. Solution is as below.
import java.io.File;
import java.util.Scanner;
import java.io.FileNotFoundException;
public class Main {
public static void main(String[] args) {
readFile();
}
public static void readFile() {
File file = new File("database/Data.txt");
try {
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
int i = scanner.nextInt();
System.out.println(i);
}
scanner.close();
}catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
Only check if those content can read using scanner or not. Content having int properly. otherwise it will throw java.util.InputMismatchException.
Are you working on a mac or windows system.
I am on windows and ".\database\Data.txt" would most probably work depending on where the file is in your file structure.

decreasing in size when reversing and storing text from a file to another using Java

I made this homework exercise to read text from a text file and store it reversed into another new file. This is the code:
import java.util.*;
import java.io.*;
public class FileEcho {
File file;
Scanner scanner;
String filename = "words.txt";
File file1 ;
PrintWriter pw ;
void echo() {
try {
String line;
file = new File( filename);
scanner = new Scanner( file );
file1 = new File("brabuhr.txt");
pw = new PrintWriter(file1);
while (scanner.hasNextLine()) {
line = scanner.nextLine();
String s = new StringBuilder(line).reverse().toString();
pw.println(s);
}
scanner.close();
} catch(FileNotFoundException e) {
System.out.println( "Could not find or open file <"+filename+">\n"+e
);
}
}
public static void main(String[] args) {
new FileEcho().echo();
}
}
and here is a picture Picture here
The question is: why is the newly generated file decreased in size despite having the same characters but reversed?
Would be great if someone can explain it because even my professor didn't know why is that.
P.S; the context of the file is just some words from the dictionary.
Also in other students computers so the problem is not from my computer
The problem is that you never closed the output stream pw, so that any pending output isn't written to the underlying file. This may cause truncation of your file.
You should have closed the output stream with pw.close() in a finally, or in a try with resources.
try (pw = new PrintWriter(file1)) {
while (scanner.hasNextLine()) {
line = scanner.nextLine();
String s = new StringBuilder(line).reverse().toString();
pw.println(s);
}
}
Your implementation can be simplified to be the following:
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Paths;
public class FileEcho {
void echo() throws IOException {
try (PrintWriter pw = new PrintWriter("brabuhr.txt")) {
Files.lines(Paths.get("words.txt"))
.map(s -> new StringBuilder(s).reverse().toString())
.forEach(pw::println);
}
}
public static void main(String[] args) throws IOException {
new FileEcho().echo();
}
}
In this example I used a 'try-with-resources' to have the PrintWriter pw autoclosed.

Writing all the java output in a txt file

I would like to know how to write all lines from the java output in a .txt file.
I've done some tests so far but I don't seem to be able to find the solution :/
Here is a small code, if you could show me with this one, it would be greatly appreciated :
The code shown below asks the user what to write in a .txt file but I want it to write all the printed lines in a .txt file without asking the user anything. Thank you
package test;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
public class Test {
public static void main(String[] args)throws Exception {
System.out.println("Hello");
System.out.println("Hi");
System.out.println("Hola");
System.out.println("Bonjour");
System.out.println("Hallo");
System.out.println("Hej");
System.out.println("Alo");
System.out.println("Ciao");
writeOutput();
}
public static void writeOutput() throws Exception {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String lineFromInput = in.readLine();
PrintStream out = new PrintStream(new FileOutputStream("output.txt"));
System.setOut(out);
out.println(lineFromInput);
out.close();
}
}
Use directly PrintStream to write the String values.
public static void main(String[] args)throws Exception {
PrintStream printStream = new PrintStream(new File("output.txt"));
// hook for closing the stream
Runtime.getRuntime().addShutdownHook(new Thread(printStream::close));
// writing
write(printStream,"Hello", "Hi", "Hola", "Bonjour", "Hallo", "Hej",
"Alo","Ciao");
// writing again
write(printStream, "A new String", "And again another one...");
}
public static void write(PrintStream printStream, String... values) throws Exception {
try{
for (String value : values){
printStream.println(value);
}
printStream.flush();
}
catch (Exception e){
// handling exception
}
}
}
java test.Test > somefile.txt

geting a multiline text with scanner class in java

In a part of my university project I have to get a text with some lines then saving it in a string or a string array.My problem is that in scanner class using methods gets only one line of the input. So I cannot get the other lines.please help me.
public class Main {
public static void main(String[] args) {
java.util.Scanner a = new java.util.Scanner(System.in);
String b = "";
while (a.hasNextLine()) {
b += a.nextLine();
}
}
}
You can try to use isEmpty to detect an enter-only input.
UPDATED:
If your input also contain a blank line, then you may specify another terminator character(s); instead of only an empty string.
public class Main {
public static void main(String[] args) {
//for example ",,"; then the scanner will stop when you input ",,"
String TERMINATOR_STRING = ",,"
java.util.Scanner a = new java.util.Scanner(System.in);
StringBuilder b = new StringBuilder();
String strLine;
while (!(strLine = a.nextLine()).equals(TERMINATOR_STRING)) {
b.append(strLine);
}
}
}
If you are building your program from command line, then there's something called "input redirection" which you can use. Here's how it works:
Let's suppose your program is:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class ScanningMultiline
{
public static void main (String[] args)
{
List<String> lines = new ArrayList<> ();
try (Scanner scanner = new Scanner (System.in))
{
while (scanner.hasNextLine ())
{
lines.add (scanner.nextLine ());
}
}
System.out.println ("Total lines: " + lines.size ());
}
}
Now suppose you have input for your program prepared in a file.
To compile the program you'd change the current directory of terminal/command prompt to the program directory and then write:
javac ScanningMultiline.java
And then to run, use input redirection like:
java ScanningMultiline < InputFile.txt
If your InputFile.txt is in another directory, just put its complete path instead like:
java ScanningMultiline < "/Users/Xyz/Desktop/InputFile.txt"
Another Approach
You can try reading your input directly from a file. Here's how that program would be written:
import java.io.IOException;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class ScanningMultiline
{
public static void main (String[] args)
{
final String inputFile = "/Users/Xyz/Desktop/InputFile.txt";
List<String> lines = new ArrayList<> ();
try (Scanner scanner = new Scanner (Paths.get (inputFile)))
{
while (scanner.hasNextLine ())
{
lines.add (scanner.nextLine ());
}
}
catch (IOException e)
{
e.printStackTrace ();
}
System.out.println ("Total lines: " + lines.size ());
}
}
This approach reads directly from a file and puts the lines from the file in a list of String.
Another Approach
You can read the lines from a file and store them in a list in a single line as well, as the following snippet demonstrates:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
public class ScanningMultiline
{
public static void main (String[] args) throws IOException
{
final String inputFile = "/Users/Xyz/Desktop/InputFile.txt";
List<String> lines = Files.readAllLines (Paths.get (inputFile));
}
}
Yohanes Khosiawan has answered a different approach so I'm not writing that one here.

Categories