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.
Related
When I'm trying to run this piece,
import java.io.*;
import java.util.Scanner;
import static java.lang.System.*;
class CSWrite1
{
public static void main(String[] args) throws IOException
{
Scanner input = new Scanner(in);
out.print("Enter the filename\t>");
String file = input.next();
out.println("Enter the text");
String text = input.next(); // IN:"Hello, How are you" --> "Hello,
try(FileWriter fw = new FileWriter(file))
{ fw.write(text); }
}
}
while giving input to text as "Hello, How are you" The file is written only with "Hello,. The remaining text after the first space is not being written into the file.
The following works for me:
import static java.lang.System.*;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class CSWrite1 {
public static void main(String[] args) {
try (Scanner input = new Scanner(in)) {
out.print("Enter file name> ");
String file = input.nextLine();
try (FileWriter fw = new FileWriter(file)) {
out.print("Enter text: ");
String text = input.nextLine(); // IN:"Hello, How are you" --> "Hello,
fw.write(text);
}
catch (IOException xIo) {
xIo.printStackTrace();
}
}
}
}
The Scanner is using delimiter, which includes space by default. What you could do (I do not know how elegant this is) is to remove delimiter.
Scanner input = new Scanner(System.in);
input.useDelimiter("");
String text=input.nextLine();
System.out.println(text);
This works for me. It is not your file writer, it is the Scanner that is doing this.
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.
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.
So in my main class called testPara, whenever I want to execute the methods in my class paragraph, I always have to write the file name inside the parameter of my methods. For example: g.readFile(file), g.countSentence(file). What would I have to do so methods won't require and I could execute just by g.count(). Maybe a global variable? This my paragraph class:
import java.util.*;
import java.util.ArrayList;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
class paragraph {
public void readFile(File filename) {
try {
Scanner scanner = new Scanner(filename);
while(scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
System.exit(0);
}
}
public void countSentences(File filename) {
int sentanceCount = 0;
String line;
String delimiters = "?!.";
try {
Scanner scanner = new Scanner(filename);
while(scanner.hasNextLine()) {
line = scanner.nextLine();
for(int i = 0; i < line.length(); i++) {
if (delimiters.indexOf(line.charAt(i)) != -1) {
sentanceCount++;
}
}
}
System.out.println("# of sentances: " + sentanceCount);
} catch (FileNotFoundException e) {
e.printStackTrace();
System.exit(0);
}
}
This is how I'm testing my methods
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class testPara {
public static void main(String args[]) {
paragraph g = new paragraph();
File file = new File("story.txt");
g.readFile(file);
System.out.println("\n");
g.countSentences(file);
}
}
This makes only sense if your Paragraph class works with the same file the whole time. Then you could just add a field private File file; or something to the Paragraph class and use a setter to set the File object once. Like so:
public class Paragraph {
private File file;
public void setFile(File file){
this.file = file;
}
....
...and in the main method:
Paragraph p = new Paragraph();
p.setFile(new File("whatever.txt"));
p.readFile();
p.countSentences();
....
Of course you'll have to modify your readFile() method (etc) so they use the new "file" class variable.
EDIT: Or, as #4castle suggested, you could use a constructor to hand over the File instance (if your class needs this instance to work properly, this would be the right approach).
Make filename an instance variable of your class Paragraph
class Paragraph {
private String filename;
. . .
// constructor taking the argument for filename
public Paragraph(String filename) {
this.filename = filename;
. . .
and have the caller pass the value in when constructing an object from that class
Paragraph g = new Paragraph("story.txt");
After that, your methods do not need the argument anymore, they
can just take the value from the instance variable. For example
public void countSentences() {
Scanner scanner = new Scanner(this.filename);
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.