How to read strings and numbers from file in java? - java

How to read from a file strings or numbers with one space between them.

You can just write a class which will read a file and remove the spaces.
package com.example.removespaces
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class RemoveSpacesInFileEx {
public static void main(String[] args) throws FileNotFoundException, IOException {
FileReader fr = new FileReader("input.txt");
BufferedReader br = new BufferedReader(fr);
FileWriter fw = new FileWriter("outfile.txt");
String line;
while((line = br.readLine()) != null)
{
line = line.trim();
line=line.replaceAll("\\s+", " ");
fw.write(line);
}
fr.close();
fw.close();
}
}

public void readData() {
File file = new File("file.txt"); //You can put your file name or your file position here
try {
Scanner sc = new Scanner(file);
while(sc.hasNext()) {
System.out.println(sc.nextLine());
} System.out.println();
}
catch (FileNotFoundException e) {
System.out.println(e.getMessage());
}
System.out.println("End of the Main");
} //This will read it from a file and print on your console

Related

Input Validation method for Java

I'm sort of new to Java and I'm learning about input validation methods but I'm struggling with an assignment that I'm trying to complete. Can someone help me? The following code is reading a file somewhere on your computer. I'm supposed to verify that the file path is correct with an input validation method. This is what I have so far:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class readFile {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter the name of your File: ");
String fileName = scan.nextLine();
File inputFile = new File(fileName);
BufferedReader reader = null;
try {
String sCurrentLine;
reader = new BufferedReader(new FileReader(inputFile));
while ((sCurrentLine = reader.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
System.out.print(e.getMessage());
} finally {
try {
if (reader != null)reader.close();
} catch (IOException ex) {
System.out.println(ex.getMessage());
ex.printStackTrace();
}
}
}
}
The easiest way to tell if the file path given is correct is to simply check if it exists:
if (inputFile.exists() && !inputFile.isDirectory()) {
// inputFile has a valid path.
}
Use following code checking.
File f = new File(filePathString);
if(f.exists() && !f.isDirectory()) {
// do something
}

Scraping Google App Store for Meta Data

I am noob in Java trying to to build a scraper in a Java which could do the following things.
Ability to read data from a CSV file.
Use the URIs in that file and scrape the complete App info from the Google Playstore.
Export the scraped data and other meta data from the CSV file into an XML file
Can any one guide me in this how to go from here ?
Till now I have made the following three classes
main.java (This is the main method where I call other two classes)
import java.io.IOException;
public class main {
public static void main(String[] args) throws IOException {
ReadCVS obj = new ReadCVS();
obj.run();
AppInfo obj1 = new AppInfo();
obj1.readFile();
}
}
ReadCVS.java (This file reads the CSV file and give the output in a txt file)
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintStream;
public class ReadCVS {
public void run() {
// Replace the file path to the appropriate path.
String csvFile = "\\Desktop\\https---play_google_com-store-apps-details-id=.csv";
BufferedReader br = null;
String line = "";
String cvsSplitBy = ";";
try {
File file = new File("\\Desktop\\output.txt");
FileOutputStream fos = new FileOutputStream(file);
PrintStream ps = new PrintStream(fos);
System.setOut(ps);
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
// use comma as separator
String[] country = line.split(cvsSplitBy);
System.out.println("URL = " + country[0] + " "
);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println("Done");
}
}
AppInfo.java (This file reads the input from the saved output.txt and tries to out put in the console. But it is not currently working)
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class AppInfo {
public void readFile(){
String fileName = "\\Desktop\\output.txt";
//read file into stream, try-with-resources
try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
The problem is that whenever I try to run this code the program get hanged and does not terminate.
Can any one help me with my problem ?

Unable to write input into a file

I have tried many times to read a user input and then write it to a file but I haven't find a solution. Here is my code...
The main class.
import java.util.HashMap;
import java.util.Scanner;
public class cShell{
static String Currentpath="C:\\";
public String Current = Currentpath;
static HashMap<String, ICommand> myhashData=new HashMap<String, ICommand>();
public static void main(String[] args)
{
myhashData.put("ltf", new cITF());
myhashData.put("nbc", new cNBC());
myhashData.put("gdb", new cGDB());
myhashData.put("Tedit", new cTedit());
String Input = "";
do{
System.out.print(Currentpath+"> ");
//String Input = "";
Scanner scan = new Scanner(System.in);
if(scan.hasNext()){
Input = scan.nextLine().trim();
}
if(Input.equals("exit")){
System.exit(0);
}
if(myhashData.containsKey(Input)){
ICommand myCommand=myhashData.get(Input);
myCommand.Execute();
}
else{
System.out.println("Invalid Command");
}
}while(!Input.equals("exit"));
}
}
This is the class that do the read and write.
import java.util.*;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
//import java.lang.System.*;
public class cTedit implements ICommand{
#Override
public void Execute() {
String filename = "";
System.out.println("Enter the file name to be edited");
Scanner scan = new Scanner(System.in);
if(scan.hasNext()){
filename = scan.nextLine();
}
String line = null;
try{
InputStreamReader ISR = new InputStreamReader(System.in);
//FileReader fileReader = new FileReader(ISR);
FileWriter fileWriter = new FileWriter(cShell.Currentpath+"\\"+filename);
BufferedReader bufferedReader = new BufferedReader(ISR);
System.out.println("Enter text into the file");
while((line = bufferedReader.readLine()) != null){
fileWriter.write(line);
}
bufferedReader.close();
}catch(FileNotFoundException ex){
System.out.println("Unable to open file '" + filename + "'");
}
catch(IOException ex){
System.out.println("Error reading file '" + filename + "'");
}
}
}
My problem is when I enter some text as user input, pressing enter doesn't stop me from entering inputs, but when I press Ctrl+z it ran into an infinite loop.
Try this one in cTedit class.
bufferedReader.readLine() will never return null in your case.
Type exit to come out of loop.
while((line = bufferedReader.readLine()) != null){
if(line.equals("exit")){
break;
}
fileWriter.write(line);
}
Use fileWriter.close() in the end.
Maybe that's not the source of your problem, but I don't think that you need to check the hasnext() condition to read a line :
if(scan.hasNext()){
filename = scan.nextLine();
}
just filename = scan.nextLine(); should be enough.
Use the following
if(Input.equals("exit") || Input.equals("")){
System.exit(0);
}
instead of
if(Input.equals("exit")){
System.exit(0);
}
In order to close the fileWriter after just before exiting add a method closeFile as below.
import java.util.;
import java.io.;
import java.nio.file.Files;
import java.nio.file.Path;
//import java.lang.System.*;
public class cTedit implements ICommand{
private FileWriter fileWriter;
#Override
public void Execute() {
// TODO Auto-generated method stub
String filename = "";
System.out.println("Enter the file name to be edited");
Scanner scan = new Scanner(System.in);
if(scan.hasNext()){
filename = scan.nextLine();
}
String line = null;
try{
InputStreamReader ISR = new InputStreamReader(System.in);
//FileReader fileReader = new FileReader(ISR);
fileWriter = new FileWriter(cShell.Currentpath+"\\"+filename);
BufferedReader bufferedReader = new BufferedReader(ISR);
System.out.println("Enter text into the file");
while((line = bufferedReader.readLine()) != null){
fileWriter.write(line);
}
bufferedReader.close();
}catch(FileNotFoundException ex){
System.out.println("Unable to open file '" + filename + "'");
}
catch(IOException ex){
System.out.println("Error reading file '" + filename + "'");
} finally {
fileWriter.close();
}
}
public void closeFile() {
fileWriter.close();
}
}
and then callCloseFile in cShell class just before exiting

Creating, writing and editing same text file in java

Let's say I have the following code:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class EditFile {
public static void main(String[] args) {
try{
String verify, putData;
File file = new File("file.txt");
file.createNewFile();
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
bw.write("Some text here for a reason");
bw.flush();
bw.close();
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
while( br.readLine() != null ){
verify = br.readLine();
if(verify != null){
putData = verify.replaceAll("here", "there");
bw.write(putData);
}
}
br.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
All I wanted to do was to write something in a text file, in my case "Some text here for a reason". Then to read data from my file, and finally to change my text from my file from "Some text here for a reason" in "Some text there for a reason". I ran the code but all it happens is to write in my file "Some text here for a reason".
I tried to figure out what could be wrong in my code, but unfortunately it was in vain. Any advice or rewrite is highly appreciated from me.
Change your code to that:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class EditFile {
public static void main(String[] args) {
try{
String verify, putData;
File file = new File("file.txt");
file.createNewFile();
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
bw.write("Some text here for a reason");
bw.flush();
bw.close();
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
while( (verify=br.readLine()) != null ){ //***editted
//**deleted**verify = br.readLine();**
if(verify != null){ //***edited
putData = verify.replaceAll("here", "there");
bw.write(putData);
}
}
br.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
The Problem is that you are calling br.readLine() twice which is provoking the application to read line1 and then line2 and in your case you have just one line which means that your program read it in the conditional form and when it comes to declaring it to the variable verify, it is stopping because you don't have anymore data to read your file.
I would do it this way:
import java.io.*;
public class EditFile {
public static void main(String[] args) {
try{
String verify, putData;
File file = new File("file.txt");
file.createNewFile();
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
bw.write("Some text here for a reason");
bw.flush();
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
while( (verify=br.readLine()) != null )
{
if(verify != null)
{
putData = verify.replaceAll("here", "there");
bw.write(putData);
}
}
br.close();
bw.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
use this code, I used it to remove logs and System.out statements in java file.
just change the matching and replacing string.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class FileReplace {
List<String> lines = new ArrayList<String>();
String line = null;
Scanner scan = null;
public void doIt() {
scan = new Scanner(System.in);
while (true) {
try {
System.out
.println("enter qualified file name ex.D:\\shiv\\shiv android all\\Main work space\\Welcomescreen1.java");
String path = scan.nextLine();
File f1 = new File(path);
FileReader fr = new FileReader(f1);
BufferedReader br = new BufferedReader(fr);
int i = 0;
while ((line = br.readLine()) != null) {
if (line.contains("System.out")) {
line = line.replace("System.out", "//");
} else if (line.contains("Log.")) {
line = line.replace("Log", "//");
}
lines.add(i, line);
i++;
}
fr.close();
br.close();
FileWriter fw = new FileWriter(f1);
BufferedWriter out = new BufferedWriter(fw);
for (int j = 0; j < lines.size(); j++) {
System.out.println(j + "." + lines.get(j));
out.append(lines.get(j));
out.newLine();
}
out.flush();
out.close();
System.out
.println("====================work done===================");
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
public static void main(String args[]) {
FileReplace fr = new FileReplace();
fr.doIt();
}
}
import java.io.*;
public class TextFile
{
public static void main(String[] args)
{
try
{
String verify, putData;
File file = new File("G:\\Dairy.txt");
file.createNewFile();
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
bw.write("I am Shah Khalid");
bw.flush();
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
while( (verify=br.readLine()) != null )
{
if(verify != null)
{
putData = verify.replaceAll("here", "there");
//bw.write(putData);
}
}
br.close();
bw.close();
}
catch(IOException e)
{
e.printStackTrace();
}
System.out.println("Shah");
}
}
There is no need to type bw.write(putData);, because it will just print the statement twice.
Whatever you want in a file, just give the correct path of the file and use the above code accordingly.
File file = new File("/tmp/my.txt");
FileWriter fw;
BufferedReader br;
BufferedWriter bw;
boolean no=false;
String line;
String data="";
String lessonPath="my new line";
try {
if(!file.exists()){
fw = new FileWriter(file);
bw = new BufferedWriter(fw);
bw.write(lessonPath);
bw.flush();
bw.close();
}else{
br = new BufferedReader(new FileReader(file));
while((line =br.readLine()) !=null){
if(!no){
data=line;
no=true;
}else{
data = data+"\n"+line;
}
}
bw = new BufferedWriter(new FileWriter(file));
bw.write(data+"\n"+lessonPath);
bw.flush();
bw.close();
}
} catch (Exception ex) {
ex.printStackTrace();
}

read multiple data in multiple files

I have a list of files in the directory C:\Users\Mahady\Desktop\Java 31122011\src\register\
they are like this....
100100545.txt
100545454.txt etc etc
in each file, file data are like this line by line:
Bob
1234
4834
London
9852
1
My question is, how do i read each files one by one in the directory and for each files read all lines except line 3. i would then like to merge this data in word and create letters. thanks
Detailed Answer....
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class FileRead {
public static void main(String[] args) {
FileReader fileReader = null;
BufferedReader bufferedReader = null;
try {
File folder = new File("C:/Users/Mahady/Desktop/Java 31122011/src/register/");
if (folder.isDirectory()) {
for (File file : folder.listFiles()) {
fileReader = new FileReader(file);
bufferedReader = new BufferedReader(fileReader);
String line = null;
int lineCount = 0;
while (null != (line = bufferedReader.readLine())) {
lineCount++;
if (3 != lineCount) {
System.out.println(line);
}
}
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (null != bufferedReader)
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Hope this would help you.
Try this:
File dir = new File("C:\\Users\\Mahady\\Desktop\\Java 31122011\\src\\register\\");
for (string fn : dir.list()) {
FileInputStream fstream = new FileInputStream(fn);
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
System.out.println (strLine);
}
in.close();
}
Obviously, you will need to add exception handling code around this skeletal implementation.

Categories