My target is to write a code which allow me to calculate number of lines in txt files from folder and his subfolders, i wrote a code which allows me to do it only for a single file, what should i change to get good result? Directory cant be specified in code.
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class Lines {
public static String getValueFromUser(String comment) {
Scanner scanner = new Scanner(System.in);
System.out.println(comment);
return scanner.nextLine();
}
public static void main(String[] args) {
String filePath = getValueFromUser("location: ");
readFileContent(filePath);
}
private static void readFileContent(String filePath) {
int numberOfLines = 0;
String textLine;
try (BufferedReader fileReader = new BufferedReader(new FileReader(filePath))) {
while ((textLine = fileReader.readLine()) != null) {
numberOfLines++;
}
System.out.println("number of lines: " + numberOfLines);
} catch (FileNotFoundException ex) {
System.out.println("no file found.");
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
To count all lines of all .txt files in a directory you'd need to iterate over the content of that directory and its subdirectories. Using the Files class this is quite easy (if you're allowed to do so):
Files.walk(Path.of(filePath )) //iterates through all files and directories in the given locaction
.filter(path -> Files.isRegularFile(path)) //we're only interested in files
.filter(path -> path.toFile().getName().endsWith(".txt")) //specifically those ending in .txt
.forEach(path -> readFileContent(path.toString())); //call your method here
Note that this will just print the number of lines for each file. If you need to get a total you should not use forEach() but maptoInt(...).sum() and return the number of lines from your method.
Related
I'm trying to show covid data in each line that will be separated into tabs (like a table) and the numeric values will be divided by the thousands separator.
I'm also trying to use a printf statement so i can specify each line to be formatted in that way but im not sure how to do that.
The result I'm looking for:
Global 213,752,662 4,519,052 655,952
What I'm getting:
Global 213752662 4519052 655952
My Code:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
public class COVIDdata {
public static void main(String[] args) throws FileNotFoundException {
//printing header//
System.out.println("Name\t\t\tTotal Cases\tNew Cases\tNew Cases");
System.out.println("\t\t\t\t\t7 Days \t\t24 Hours");
System.out.println("--------------------------------------------------------------------------------------");
//opening the file//
try {
File file = new File("C:\\Desktop\\COVID-19GlobalData.txt");
Scanner scan = new Scanner(file);
while (scan.hasNextLine()) {
System.out.println(scan.nextLine());
}
while(scan.hasNext()) {
System.out.printf("%,d\n" , int);
}
scan.close();
} catch (IOException e) {
System.out.println("Error reading file");
e.printStackTrace();
}
}
}
This loop will exhaust the entire file scanner and print the file as-is with no formatting
while (scan.hasNextLine()) {
System.out.println(scan.nextLine());
}
You need to parse the lines then include the tabs in your output between several numbers. Something like
while (scan.hasNextLine()) {
String line = scan.nextLine();
String[] parts = line.split("\\s+");
System.out.printf("Global\t%,d\t%,d\n", Long.parseLong(parts[1]), Long.parseLong(parts[2]));
}
Good Morning. Having trouble with a parser using split method. Goal is to read in txt file, extract should statements, then write a new txt file with those should statements. I have it working when the text is on one continuous line. If I have a new line in the txt file, rewrites the file with just the last line. Possibly the structure of my loops? Also any suggestions for saving new file from the directory in which it was opened? Thank you
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
/*This Program Will launch a File Explorer.
User will then chose a .txt file to be parsed.
A new file will be created labeled "Parsed_(Document Name)".*/
public class Parser {
#SuppressWarnings("resource")
public static void main(String[] args) {
JFileChooser chooser = new JFileChooser();
Scanner userFile = new Scanner(System.in);
int returnVal = chooser.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
try {
System.out.println("You chose to open this file: " + chooser.getSelectedFile().getName() + "\n");
File file = new File(chooser.getSelectedFile().getName());
String newFile = ("Parsed_" + file);
userFile = new Scanner(file);
while (userFile.hasNextLine()) {
String document = userFile.nextLine();
// Line breaks used by Parser
String[] sentences = document.split("\\.|\\?|\\!|\\r");
List<String> ShouldArray = new ArrayList<String>();
for (String shouldStatements : sentences) {
if (shouldStatements.contains("Should") || shouldStatements.contains("should"))
ShouldArray.add(shouldStatements);
}
FileWriter writer = new FileWriter(newFile);
BufferedWriter bw = new BufferedWriter(writer);
for (String shallStatements : ShouldArray) {
System.out.println(shallStatements);
bw.append(shallStatements);
bw.newLine();
}
System.out.println("\nParsed Document Created: " + newFile);
JOptionPane.showMessageDialog(null, "Parsed Document Created: " + newFile);
bw.close();
writer.close();
}
userFile.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
Test file 1 (works!)
Hello all. Here is a a packing list. You Should have a toothbrush. You should have a Phone charger. And you definitely should have your wallet!
Test file 1 output:
You Should have a toothbrush
You Should have a Phone charger
And you definitely should have your wallet
Test file 2 (Only printing last line)
Hello all. Here is a a packing list. You Should have a toothbrush. You Should have a Phone charger.
Here is some random text to show the parser will not include this.
You definitely should have your wallet!
test file 2 output:
You definitely should have your wallet
You need to create your result array outside of the loop
/** Placed here**/
List<String> ShouldArray = new ArrayList<String>();
while (userFile.hasNextLine()) {
String document = userFile.nextLine();
// Line breaks used by Parser
String[] sentences = document.split("\\.|\\?|\\!|\\r");
/** REMOVED HERE **/
for (String shouldStatements : sentences) {
if (shouldStatements.contains("Should") || shouldStatements.contains("should"))
ShouldArray.add(shouldStatements);
}
......
otherwise you will only gather the results of your last loop.
Basically what your code was doing:
cut up file in lines
take each line
take next line
make a result board.
write results on board
take next line
erase board
write results on board
take next line
erase board
write results on board
and then at the end there is only a limited resultset on your board
You are overriding your Arraylist within the loop, however you don't actually need it
File file = chooser.getSelectedFile();
System.out.println("You chose to open this file: " + file.getName() + "\n");
String newFile = "Parsed_" + file.getName();
// open all closable objects using try-with-resources
try (Scanner userFile = new Scanner(file);
BufferedWriter bw = new BufferedWriter(new FileWriter(newFile))) {
while (userFile.hasNextLine()) {
String document = userFile.nextLine();
// Line breaks used by Parser
String[] sentences = document.split("\\.|\\?|\\!|\\r");
for (String s : sentences) {
if (s.contains("Should") || s.contains("should")) {
System.out.println(s);
bw.append(s);
bw.newLine();
}
}
System.out.println("\nParsed Document Created: " + newFile);
JOptionPane.showMessageDialog(null, "Parsed Document Created: " + newFile);
// bw.close(); // not needed anymore
I've refactored the code, removing the "ShouldArray", which is not needed.
Pseudocode
While there are lines to read in the In file
Read each line
Split each line into Array of sentences
Loop through each sentence
If each sentence contains Should or should Then
Write sentence to Out file
End If
End Loop
End While
Close Out file
Close In file
The code below works with:
Multi line:
Hello all. Here is a a packing list.
You Should have a toothbrush. You Should have a Phone charger.
Here is some random text to show the parser will not include this.
You definitely should have your wallet!
Single line:
Hello all. Here is a a packing list. You Should have a toothbrush. You should have a Phone charger. And you definitely should have your wallet!
import java.util.Scanner;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.File;
public class ShouldStringsParser {
public ShouldStringsParser(String inFile, String outFile) throws IOException {
File file = new File(inFile);
FileWriter writer = new FileWriter(outFile);
BufferedWriter bw = new BufferedWriter(writer);
Scanner userFile;
userFile = new Scanner(file);
String[] sentences;
while (userFile.hasNextLine()) {
String line = userFile.nextLine();
System.out.println(line);
sentences = line.split("\\.|\\?|\\!|\\r");
for (String shouldStatements : sentences) {
if (shouldStatements.contains("Should") || shouldStatements.contains("should")) {
System.out.println(">>>" + shouldStatements);
bw.append(shouldStatements);
bw.newLine();
}
}
}
bw.close();
writer.close();
userFile.close();
}
public static void main(String[] args) {
try {
new ShouldStringsParser("inDataMultiLine.txt", "outDataMultiLine.txt");
new ShouldStringsParser("inDataSingleLine.txt", "outDataSingleLine.txt");
} catch (IOException e) {
e.printStackTrace();
}
}
}
I am trying to search a string in a file in java and this is what, I tried . In the below program I am getting output as No Data Found and I am sure that the file has the word which I am searching
import java.io.*;
import java.util.Scanner;
public class readfile {
static String[] list;
static String sear = "CREATE";
public void search() {
Scanner scannedFile = new Scanner("file.txt");
while (scannedFile.hasNext()) {
String search = scannedFile.next();
System.out.println("SEARCH CONTENT:"+search);
if (search.equalsIgnoreCase(sear)) {
System.out.println("Found: " +search);
}
else {
System.out.println("No data found.");
}
}
}
public static void main (String [] args) throws IOException {
readfile read = new readfile();
read.search();
}
}
Don't do:
search.equalsIgnoreCase(sear)
Try:
search.toUpperCase().contains(sear)
I think the search is the whole String of the File, so you never would become true with equals.
Use nextLine() instead of next() and then use split. Like this :
What's the difference between next() and nextLine() methods from Scanner class?
Difference :
next() can read the input only till the space. It can't read two words separated by space. Also, next() places the cursor in the same line after reading the input.
nextLine() reads input including space between the words (that is, it reads till the end of line \n). Once the input is read, nextLine() positions the cursor in the next line.
Use following code :
String search = scannedFile.nextLine();
String[] pieces = data.split("\\s+");
for(int i=0; i<pieces.length(); i++)
{
if(pieces[i].equalsIgnoreCase(sear))
{
System.out.println("Found: " +search);
}
else
{
System.out.println("No data found.");
}
}
Ok, here is my understanding of your program.
You search in the file file.txt the word CREATE.
To do so, you read each word in the file and if it is CREATE you print Found create.
The issue here is that for every word in the file, if it isn't CREATE you print No data found.
Instead you should wait for the end of the file and then if you haven't found it you will print the error message.
Try this :
import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class readfile {
static String[] list;
static String sear = "CREATE";
public void search() throws IOException {
List<String> saveAllLinesForRewriting = new ArrayList<String>();
// Need to read file line by line
BufferedReader bufferedReader = new BufferedReader(new FileReader("file.txt"));
String saveLine;
while ((saveLine = bufferedReader.readLine()) != null) {
saveAllLinesForRewriting.add(saveLine);
}
bufferedReader.close();
// Check if your word exists
if (saveAllLinesForRewriting.toString().contains(sear)) {
System.out.println("Found: " + sear);
} else {
System.out.println("No data found.");
}
}
public static void main(String[] args) throws IOException {
readfile read = new readfile();
read.search();
}
}
Instead of reading file using scanner, first create a file resource to read by adding the below line
File file = new File("Full Path of file location");
before
Scannner scannedfile = new Scanner("file.txt");
and change the above line to
Scanner scannedfile = new Scanner(file);
rest your code is working fine.
The problem is that the scanner is scanning the String "file.txt" and not the file.
To fix this you have to do what amit28 says. Your finally code is as follows
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
public class readfile {
static String[] list;
static String sear = "CREATE";
public void search() {
File f = new File("file.txt");
Scanner scannedFile;
try {
scannedFile = new Scanner(f);
while (scannedFile.hasNext()) {
String search = scannedFile.next();
System.out.println("SEARCH CONTENT:"+search);
if (search.equalsIgnoreCase(sear)) {
System.out.println("Found: " +search);
}
else {
System.out.println("No data found.");
}
}
} catch (FileNotFoundException e) {
// FIXME Auto-generated catch block
e.printStackTrace();
}
}
public static void main (String [] args) throws IOException {
readfile read = new readfile();
read.search();
}
}
dear all here i have this code:
File file = new File("flowers_petal.txt");
Scanner in = new Scanner(file);
while(in.hasNext()){
String line = in.nextLine();
System.out.println(line);
I want to read from a file and print each line, but this code doesn't work because of some exceptions (throw exception??), how can i put it in a way that it would read from the flowers.txt file, which is on my desktop and will print each line from this file in the console?
Recheck your code
File file = new File("flowers_petal.txt"); // This is not your desktop location.. You are probably getting FileNotFoundException. Put Absolute path of the file here..
while(in.hasNext()){ // checking if a "space" delimited String exists in the file
String line = in.nextLine(); // reading an entire line (of space delimited Strings)
System.out.println(line);
SideNote : use FileReader + BufferedReader for "reading" a file. Use Scanner for parsing a file..
Here you go.. Full code sample. Assuming you put you file in C:\some_folder
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class FileReader {
public static void main(String args[]) {
File file = new File("C:\\some_folder\\flowers_petal.txt");
Scanner in;
try {
in = new Scanner(file);
while (in.hasNext()) {
String line = in.nextLine();
System.out.println(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
You are checking for the wrong condition, you need to check for hasNextline() instead of hasNext(). So the loop will be
while(in.hasNextLine()){
String line = in.nextLine();
System.out.println(line);
}
Consider these 2 points :
the current location you are giving in your file is not valid (if
your .java (source) file is not on Desktop), so give the full path
for your file.
the new Scanner(File file) throws FileNotFoundException, so you have to put the code in try-catch block or just use throws.
Your code may look like this :
try {
File file = new File("path_to_Desktop/flowers_petal.txt");
Scanner in = new Scanner(file);
while(in.hasNextLine()){
String line = in.nextLine();
System.out.println(line);
}
} catch (FileNotFoundException e){
e.printStackTrace();
}
try this
public static void main(String[] args) throws FileNotFoundException {
//If your java file is in the same directory as the text file
//then no need to specify the full path ,You can just write
//File file = new File("flowers_petal.txt");
File file = new File("/home/ashok/Desktop/flowers_petal.txt");
Scanner in = new Scanner(file);
while(in.hasNext()){
System.out.println(in.nextLine());
}
in.close();
}
NOTE :I am using linux ,If you are using windows your desktop path would be different
Try this................
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class BufferedReaderExample {
public static void main(String[] args) {
try (BufferedReader br = new BufferedReader(new FileReader("C:\\testing.txt")))
{
String sCurrentLine;
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
give your exact path in the FileReader("exact path must be here...")
source: http://www.mkyong.com/java/how-to-read-file-from-java-bufferedreader-example/
I am trying to get a program to work. The input is a source file with lines of text. The output is a target file with the original line of text but in reversed.
ex.
abcd --> dcba
efgh hgfe
1234 4321
I have looked at a couple of similar questions, but they have gone about this in a different way than I have, and that doesn't exactly solve this individual problem. I have read it through and I think I am just over thinking this. I would greatly appreciate input on why my code is not outputting at all to the target file. I made a stack trace, and it prints all the way through perfectly fine.
Thanks,
code:
(command line arguments: source2.txt target2.txt
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java. util.Scanner;
/**
This program copies one file to another.
*/
public class Reverse
{
public static void main(String[] args) throws IOException
{
try{
String source = args[0];
String target = args[1];
File sourceFile=new File(source);
Scanner content=new Scanner(sourceFile);
PrintWriter pwriter =new PrintWriter(target);
while(content.hasNextLine())
{
String s=content.nextLine();
StringBuffer buffer = new StringBuffer(s);
buffer=buffer.reverse();
String rs=buffer.toString();
pwriter.println(rs);
}
content.close();
pwriter.close();
}
catch(Exception e){
System.out.println("Something went wrong");
}
}
}
What output are you seeing??
PrintWriter suppresses IOException and sets an error flag instead; you should use an
OutputStreamWriter().
Methods in this class never throw I/O exceptions, although some of its constructors may. The client may inquire as to whether any errors have occurred by invoking checkError().
Also, don't handle an exception with "something went wrong"; at the very least dump the stack trace so you know what and where it went wrong.
That said, I would probably output each line read to the console, like so:
System.out.println("** Read ["+s+"]");
to confirm I was actually reading the file.
import java.io.*;
import java.util.*;
class Driver {
public static void main(String[] args) {
ReverseFile demo = new ReverseFile();
demo.readFile("source2.txt");
demo.reverse("target2.txt");
}
}
class ReverseFile {
// Declare a stream of input
DataInputStream inStream;
// Store the bytes of input file in a String
ArrayList<Character> fileArray = new ArrayList<Character>();
// Store file sizes to see how much compression we get
long inFileSize;
long outFileSize;
// Track how many bytes we've read. Useful for large files.
int byteCount;
public void readFile(String fileName) {
try {
// Create a new File object, get size
File inputFile = new File(fileName);
inFileSize = inputFile.length();
// The constructor of DataInputStream requires an InputStream
inStream = new DataInputStream(new FileInputStream(inputFile));
}
// Oops. Errors.
catch (FileNotFoundException e) {
e.printStackTrace();
System.exit(0);
}
// Read the input file
try {
// While there are more bytes available to read...
while (inStream.available() > 0) {
// Read in a single byte and store it in a character
char c = (char)inStream.readByte();
if ((++byteCount)% 1024 == 0)
System.out.println("Read " + byteCount/1024 + " of " + inFileSize/1024 + " KB...");
// Print the characters to see them for debugging purposes
//System.out.print(c);
// Add the character to an ArrayList
fileArray.add(c);
}
// clean up
inStream.close();
System.out.println("Done!!!\n");
}
// Oops. Errors.
catch (IOException e) {
e.printStackTrace();
System.exit(0);
}
// Print the ArrayList contents for debugging purposes
//System.out.println(fileArray);
}
public void reverse(String fileName) throws IOException {
FileWriter output = new FileWriter(fileName);
for (int i = fileArray.size() - 1; i >= 0; i++) {
try {
output.write(fileArray.get(i));
}
catch (IOException e) {
e.printStackTrace();
}
}
output.close();
}
}
That should work. If not, tell me and I'll look into the problem further.
I did some modification to your code..
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class Reverse
{
public static void main(String[] args) throws IOException
{
try{
// String source = args[0];
// String target = args[1];
File sourceFile=new File("C:/Users/Ruchira/Downloads/in.txt");//input File Path
File outFile=new File("C:/Users/Ruchira/Downloads/out.txt");//out put file path
Scanner content=new Scanner(sourceFile);
PrintWriter pwriter =new PrintWriter(outFile);
while(content.hasNextLine())
{
String s=content.nextLine();
StringBuffer buffer = new StringBuffer(s);
buffer=buffer.reverse();
String rs=buffer.toString();
pwriter.println(rs);
}
content.close();
pwriter.close();
}
catch(Exception e){
System.out.println("Something went wrong");
}
}
}
This will work