How to read from a file and then analyze this data? - java

I am a begginer(recently began learning) at programming in Java and I need help.
I have to read from a file, which contains numbers. I would like to make a method for reading from a file. Then I need to analyze this data and write it in another file.
What I strugle with is if I make a method just to read from a file or do I also have to save this read data into a variable. Where should this variable be declared inside a method (if is inside, how do I use it outside), if is outside how do I use it inside a method and also outside. Can anyone help me clarify this? What am I doing wrong?
My code of what I wrote until now. File from which I had to read has houndreds of numbers.
public class Test1 {
public static void main(String[] args) {
String nameFile = "numbers.txt";
File file = new File(nameFile);
String contentFile ="";
}
//Method for reading a .txt file
private static String readFromFile(String nameFile, String contentFile) {
String line = "";
try {
BufferedReader read = new BufferedReader(new FileReader(nameFile));
while((line = read.readLine()) != null) {
line = contentFIle;
}
read.close();
} catch (IOException e) {
System.out.println("There was an error reading from a file");
}
return line;
}
}

Theoretically speaking: mathematical functions get input variables, they preform some transformation on the variables and output the result of the transformation.
For example: f(x) = x - 1, g(x) = x * 2
You can chain functions in a way that one functions output will be the other function input: g(f(2)). In this case, the number 2 is used as an input for function f(x) and the output of f(x) is the input of g(x).
Functions and methods in programming can work in a similar way, but It may be more readable to save function output into meaningful variable names, and then to apply these variables to the next function.
Instead of doing: outputText(processText(readText(someFilename)))
You can write (pseudocode):
someFilename = 'foo'
text = readText(someFilename)
processed = processText(text)
outputText(processed)
In java and in your context this would look like the following:
public class Test1 {
public static void main(String[] args) {
String nameFile = "numbers.txt";
String contentFile = readFromFileByName(nameFile);
String altered = processText(contentFile);
saveToFile(altered, "processed.txt");
}
private static String readFromFileByName(String nameFile) {
String fullRead = "";
try {
File file = new File(nameFile);
BufferedReader read = new BufferedReader(new FileReader(file));
String line; // define line variable
while((line = read.readLine()) != null) {
fullRead += line; // pay attention for the altered code
}
read.close();
} catch (IOException e) {
System.out.println("There was an error reading from a file");
} finally {
return fullRead;
}
}
private static List<Integer> stringToIntList(String string) {
return Arrays
.stream(text.split(", "))
.map(Integer::parseInt)
.collect(Collectors.toList());
}
private static String processText(String text) {
String processed = text.replace('H', 'h'); // Some heavy processing :)
return processed;
}
private static void saveToFile(String text, String fileName) {
// save <text> to file with filename <filename>
}
}

1) Line is the variable that you have read to. So you shouldn't change its value.
line = contentFIle;
if you need only first line this method should look like:
private static String readFromFile(String nameFile) {
String line = "";
try {
BufferedReader read = new BufferedReader(new FileReader(nameFile));
line = read.readLine();
read.close();
} catch (IOException e) {
System.out.println("There was an error reading from a file");
}
return line;
}
if you need a list of this:
List<String> lines = Collections.emptyList();
try {
Files.readAllLines(Paths.get(fileName), StandardCharsets.UTF_8);
} catch (IOException e) {
// do something
e.printStackTrace();
}
return lines;
2) Also you don't call readFromFile function. So you need to change the main method:
public static void main(String[] args) {
String nameFile = "numbers.txt";
String contentFile = readFromFile(nameFile);
}
3)For your particular case, there's no sense to call readFromFile with String contentFile because you don't use this variable.

Related

Scanning integer and string from file in Java

I'm new to Java and I have to read from a file, and then convert what I have read into variables. My file consists of a fruit, then a price and it has a long list of this. The file looks like this:
Bananas,4
Apples,5
Strawberry,8
...
Kiwi,3
So far I have created two variables(double price and String name), then set up a scanner that reads from the file.
public void read_file(){
try{
fruits = new Scanner(new File("fruits.txt"));
print_file();
}
catch(Exception e){
System.out.printf("Could not find file\n");
}
}
public void print_file(){
while(fruits.hasNextLine()){
String a = fruits.nextLine();
System.out.printf("%s\n", a);
return;
}
}
Currently I am only able to print out the entire line. But I was wondering how I could break this up to be able to store the lines into variables.
So your string a has an entire line like Apples,5. So try to split it by comma and store it into variables.
String arr[] = a.split(",");
String name = arr[0];
int number = Integer.parseInt(arr[1]);
Or if prices are not integers, then,
double number = Double.parseDouble(arr[1]);
Using java 8 stream and improved file reading capabilities you can do it as follows. it stores item and count as key value pair in a map. It is easy to access by key afterwards.
I know this Maybe too advance but eventually this will help you later when getting to know new stuff in java.
try (Stream<String> stream = Files.lines(Paths.get("src/test/resources/items.txt"))) {
Map<String, Integer> itemMap = stream.map(s -> s.split(","))
.collect(toMap(a -> a[0], a -> Integer.valueOf(a[1])));
System.out.println(itemMap);
} catch (IOException e) {
e.printStackTrace();
}
output
{Apples=5, Kiwi=3, Bananas=4, Strawberry=8}
You can specify a delimiter for the scanner by calling the useDelimiter method, like:
public static void main(String[] args) {
String str = "Bananas,4\n" + "Apples,5\n" + "Strawberry,8\n";
try (Scanner sc = new Scanner(str).useDelimiter(",|\n")) {
while (sc.hasNext()) {
String fruit = sc.next();
int price = sc.nextInt();
System.out.printf("%s,%d\n", fruit, price);
}
} catch (Exception e) {
e.printStackTrace(System.out);
}
}
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Test {
public static void main(String[] args) {
BufferedReader reader;
try {
reader = new BufferedReader(new FileReader(
"C://Test/myfile.txt")); //Your file location
String line = reader.readLine(); //reading the line
while(line!=null){
if(line!=null && line.contains(",")){
String[] data = line.split(",");
System.out.println("Fruit:: "+data[0]+" Count:: "+Integer.parseInt(data[1]));
}
//going over to next line
line = reader.readLine();
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

How to replace an string after a specific line in a file using java

I have a situation similar where I need to change a line in a batch file if similar string not found.
Suppose I have a code like below in batch(I know it is not correct code as it a dummy only)
public static void main(String[] args) {
if (user == '1234') {
ENV DEV
set DB myDBDEV
set Excel myExecelDEV
set API MyAPIURLDEV
} elseif (user == '5678') {
ENV UAT
set DB myDBUAT
set Excel myExecelUAT
set API MyAPIURLUAT
}
}
}
Now I want java to read above file, find ENV as DEV and change the value like myDBDEV, myExecelDEV, MyAPIURLDEV etc.
I am able to find the line number by using below code
FileInputStream fis = new FileInputStream("C:\\Users\\owner\\Desktop\\batch\\MYbatch-env.csh");
InputStreamReader input = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(input);
String data;
String result = new String();
int i=0;
while ((data = br.readLine()) != null) {
i++;
if(data.contains("ENV DEV")) {
System.out.println("line number -> "+i);
}
result = result.concat(data + "\n");
}
I have tried below code but that was not return line number so I use above approach
Finding line number of a word in a text file using java
I also tried below approach but it seems not working
How to replace an string after a specific line in a file using java
Now problem statement is replaceAll function will remove all key but I want to remove the next string of key means value. and it is a text as string not a hashmap kind thing,
In if block if DB string is myDBDEV2 then I want to change the values to myDBDEV
Example:
If below string found
ENV DEV
Then below value should check value of key DB and replace if not found required value
set DB myDBDEV
set Excel myExecelDEV
set API MyAPIURLDEV
And main thing is code should make change in if block only, else if variables should be affected as an file example I have shown in above URL.
Below solution work for me
public static void main(String[] args) throws Exception {
String filepath= "C:\\Users\\Demo\\Desktop\\batch\\Demo.sh";
FileInputStream fis = new FileInputStream(filepath);
InputStreamReader input = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(input);
String data;
String result = new String();
int lineNumber=0;
int i=0;
while ((data = br.readLine()) != null) {
i++;
if(data.contains("My String data")) {
System.out.println("line number -> "+i);
lineNumber=i;
break;
}
result = result.concat(data + "\n");
}
br.close();
lineNumber=lineNumber+1;
System.out.println(lineNumber);
String Mystring =" Mystring";
String Mystringline = Files.readAllLines(Paths.get(filepath)).get(lineNumber-1); // get method count from 0 so -1
System.out.println("Line data ->> "+Mystringline);
if(!Mystringline.equalsIgnoreCase(Mystring)) {
setVariable(lineNumber, Mystring, filepath);
}else {
System.out.println("Mystring is already pointing to correct DB");
}
System.out.println("Succesfully Change");
}
public static void setVariable(int lineNumber, String data, String filepath) throws IOException {
Path path = Paths.get(filepath);
List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
lines.set(lineNumber - 1, data);
Files.write(path, lines, StandardCharsets.UTF_8);
}
}

How to import an online CSV file into Java and use each column as a variable?

I am trying to import a CSV file online which contains 6 fields. I am trying to import from a web link. I am able to download the file and use the file name as well. What I am trying to do is to read the data from the file and output it to my program.
So far I have this:
public class Element {
public static final String CSV_FILE_URL = "http://www.google.com/File.csv"; //Actual URl not published
public static void main(String[] args) throws IOException {
URL url = new URL(CSV_FILE_URL);
Scanner input =
new Scanner(url.openConnection().getInputStream());}
int number ;
String symbol;
String name;
int group;
int period;
double weight;
It might be a good idea to not use a Scanner but read the file line based, transform the lines into elements and then work on these like this:
public static void main(String[] args) {
try {
URL url = new URL("http://www.google.com/File.csv");
try(InputStream in = url.openStream();
InputStreamReader inr = new InputStreamReader(in);
BufferedReader br = new BufferedReader(inr)) {
String line = br.readLine();
while(line != null) {
//Best case: no String separation, no ; contained in data items. If not
//you need some other way to split this
String[] elements = line.split(";");
//Deal with that one line
//Get next line
line = br.readLine();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}

BufferedReader not reading complete .txt file

I'm trying to read a moderately sized txt file (65,00 words) into a String, then a string array. The bufferedreader throws the "could not read file" catch. When I clear it, a small part of the contents of the text file is shown in the system.out. I do not get the error with smaller text files. I'm a beginner and I'm having a lot of trouble trying to narrow down the issue.
Why isn't the BufferedReader ingesting the entire file? And why is the "could not read file" error being thrown?
public class Main {
public static void main(String[] args) {
final Guid Main = new Guid(); //creates instance of Guid
Main.mergeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0)
{
merge();
}
});
}
static void merge()
{
//read file and turn into string
String pathone = open(Guid.PathOne);
System.out.print(pathone);
//parse and format
//String[] oneArray = pathone.replace("\n"," ").split(" ");
//get pathtwo text
//String pathtwo = open(Guid.PathTwo);
//parse and format
//load into array
//compare array entries
//add new array entry
//sort array
//write array to paththree file
//for(int i=0; i<oneArray.length;i++)
//{
//System.out.println(oneArray[i]);
//}
}
public static String open(JTextArea Path)
{
String record = null;
FileReader frFile = null;
try {
frFile = new FileReader(Path.getText());//gets file from Path
BufferedReader brFile = new BufferedReader(frFile);//creates buffered reader
record = brFile.readLine() + "\n"; //gets contents of file and puts it into a string
brFile.mark(0);
while (brFile.read() != -1) //loop to read the rest of the text file
{
brFile.reset();
record = record + brFile.readLine() + "\n";
brFile.mark(0);
}
}
catch (FileNotFoundException e) //catch path is in error
{
JFrame frame = null;
JOptionPane.showMessageDialog(frame, "Could not find file.");
}
catch (IOException e) //catch if file cannot be read
{
JFrame frame = null;
JOptionPane.showMessageDialog(frame, "Could not read file.");
}
try { //closes file
frFile.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return record;
}
}
Do in this way. Remove reset() and mark() methods if you want to read the entire file.
StringBuilder record = new StringBuilder();
BufferedReader brFile = new BufferedReader(frFile);
String line = null;
while ((line = brFile.readLine()) != null) {
record.append(line).append("\n");
}
Note:
Don't forget to close the stream.
Use finally block to close the stream
Use StringBuilder or StringBuffer to append the string.
Use System.getProperty("line.separator") to get the system specific line separator
Have a look at Java7 try-with-resources Statement advantage
readLine will read the first line of your document.
Try with it (not tested):
String lineReaded;
while ((lineReaded=brFile.readLine())!=null)
{
record +=linereaded+"\n";
}
Niko
You might like to use Files.readAllLines

Array variable initialization error in Java

I am trying to write a Java program that reads an input file consisting of URLs, extracts tokens from these, and keeps track of how many times each token appears in the file. I've written the following code:
import java.io.*;
import java.net.*;
public class Main {
static class Tokens
{
String name;
int count;
}
public static void main(String[] args) {
String url_str,host;
String htokens[];
URL url;
boolean found=false;
Tokens t[];
int i,j,k;
try
{
File f=new File("urlfile.txt");
FileReader fr=new FileReader(f);
BufferedReader br=new BufferedReader(fr);
while((url_str=br.readLine())!=null)
{
url=new URL(url_str);
host=url.getHost();
htokens=host.split("\\.|\\-|\\_|\\~|[0-9]");
for(i=0;i<htokens.length;i++)
{
if(!htokens[i].isEmpty())
{
for(j=0;j<t.length;j++)
{
if(htokens[i].equals(t[j].name))
{ t[j].count++; found=true; }
}
if(!found)
{
k=t.length;
t[k].name=htokens[i];
t[k].count=1;
}
}
}
System.out.println(t.length + "class tokens :");
for(i=0;i<t.length;i++)
{
System.out.println(
"name :"+t[i].name+" frequency :"+t[i].count);
}
}
br.close();
fr.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
But when I run it, it says: variable t not initialized.. What should I do to set it right?
Arrays in Java are fixed length, so I think what you really want to do is use a List<Tokens>
e.g.
List<Tokens> t = new ArrayList<Tokens>();
and
t.add(new Tokens(...))
unless you know in advance the number of items you'll have.
Initialize it:
// Declaration:
Tokens[] t;
// Initialization:
t = new Tokens[10]; // (Or whatever your desired length is)
You can combine declaration and initialization, and many do. I'm not a fan of doing so, but:
Tokens[] t = new Tokens[10];
You'll have the same issue with htokens.
You may want to look at the List interface (and its various implementations) instead of using an array.
Your code declares that t will represent an array of Tokens.
However, it does not define that array.
Per the Java Documentation, you need a line like:
t = new Tokens[10]; // Or however large the array should be
You are not initializing Tokens t[]; before using it.
EDIT : You need to it as below :
Tokens[] t = new Tokens[100]; // 100 is just an example
Or use List<Tokens>.
The modified code : < as per Brian Agnew's answer >
import java.io.*;
import java.net.*;
import java.util.*;
public class Main {
static class Tokens
{
String name;
int count;
Tokens(String str,int c)
{
name=str;
count=c;
}
}
public static void main(String[] args) {
String url_str,host;
String htokens[];
URL url;
boolean found=false;
List<Tokens> t = new ArrayList<Tokens>();
int i,j,k;
try
{
File f=new File("urlfile.txt");
FileReader fr=new FileReader(f);
BufferedReader br=new BufferedReader(fr);
while((url_str=br.readLine())!=null)
{
url=new URL(url_str);
host=url.getHost();
htokens=host.split("\\.|\\-|\\_|\\~|[0-9]");
for(i=0;i<htokens.length;i++)
{
if(!htokens[i].isEmpty())
{
found=false;
for(j=0;j<t.size();j++)
{
if(htokens[i].equals(t.get(j).name))
{
k=t.get(j).count+1;
t.set(j,new Tokens(htokens[i],k));
found=true;
break;
}
}
if(!found)
{
t.add(new Tokens(htokens[i],1));
}
}
}
}
System.out.println(t.size() + "class tokens :");
for(i=0;i<t.size();i++)
{
System.out.println("name :"+t.get(i).name+" freq :"+t.get(i).count);
}
br.close();
fr.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Just to mention, you should not use C-like array syntax, i.e. use
String[] names = { "Walter", "Hans", "Bill" };
Instead of
String names[] = { "Walter", "Hans", "Bill" };

Categories