Convert String value from a file to integer - java

I am reading, from a file, integer values that I should use to calculate the function multiple.
However, after converting to integer, it appears that the integer variable doesn't hold them for further calculation.
Any help please?
import java.io.*;
public class Functions {
int values, mul7, mul11, mul13;
public static void main (String []args) {
Functions go = new Functions ();
go.multiple();
// will call functions here
}
public void multiple () {
int a = 7;
int b = 11;
int c = 13;
try {
File inputFile = new File ("JavaInputData.txt");
FileReader fileReader = new FileReader (inputFile);
BufferedReader reader = new BufferedReader (fileReader);
String line = null;
while ((line = reader.readLine()) !=null)
{
values = Integer.parseInt(line);
System.out.println(values);
}
mul7 = values % a;
mul11 = values %b;
mul13 = values %c;
System.out.println(mul7);
reader.close();
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
}

Perform the calculation and output in the loop body. Something like,
while ((line = reader.readLine()) != null)
{
values = Integer.parseInt(line);
System.out.println(values);
mul7 = values % a;
mul11 = values % b;
mul13 = values % c;
System.out.printf("mul7 = %d, mul11 = %d, mul13 = %d%n", mul7, mul11, mul13);
}
Also, I suggest you use a try-with-resources to close() your Reader;
try (File inputFile = new File ("JavaInputData.txt");
FileReader fileReader = new FileReader (inputFile);
BufferedReader reader = new BufferedReader (fileReader)) {
That way you don't have to call close() explicitly. But, if you're going to call close() explicitly; please do so in a finally block.

Related

Editing a text File in Java and saving it as a new text file

I have a text file with 5 lines, I wish to read in those lines and be able to number them 1 - 5, and save them in a different file. The numbers begin before the start of the line. I have tried to hard code in a loop to read in the number but I keep getting errors.
public class TemplateLab5Bronze {
static final String INPUT_FILE = "testLab5Bronze.txt";
static final String OUTPUT_FILE = "outputLab5Bronze.txt";
public static void main(String[] args) {
try {
FileReader in = new FileReader(INPUT_FILE);
PrintWriter out = new PrintWriter(OUTPUT_FILE);
System.out.println("Working");
BufferedReader inFile = new BufferedReader(in);
PrintWriter outFile = new PrintWriter(out);
outFile.print("Does this print?\n");
String trial = "Tatot";
outFile.println(trial);
System.out.format("%d. This is the top line\n", (int) 1.);
System.out.format("%d. \n", (int) 2.);
System.out.format("%d. The previous one is blank.\n", (int) 3.);
System.out.format("%d. Short one\n", (int) 4.);
System.out.format("%d. This is the last one.\n", (int) 5.);
/*if(int j = 1; j < 6; j++){
outFile.print( i + trial);
}*/
String line;
do {
line = inFile.readLine();
if (line != null) {
}
} while (line != null);
inFile.close();
in.close();
outFile.close();
} catch (IOException e) {
System.out.println("Doesnt Work");
}
System.out.print("Done stuff!");
}
}
This is all the code I have so far, excluding the import statements, the commented for loop is what I was trying to use. Is there another way to do this?
One way to do it is to add to the printWriter while looping through the existing file:
FileReader fr = new FileReader("//your//path//to//lines.txt");
BufferedReader br = new BufferedReader(fr);
try (PrintWriter writer = new PrintWriter("//your//other//path//newlines.txt", "UTF-8")) {
String line;
int num = 1;
while ((line = br.readLine()) != null) {
writer.println(num + ". " + line);
num++;
}
}
Note: I didn't put in any catch statements, but you might want to catch some/all of the following: FileNotFoundException, UnsupportedEncodingException, IOException
You don't need two PrintWriters. Use only one.
PrintWriter outFile = new PrintWriter(OUTPUT_FILE);
You can simply use a counter instead of a for loop (which you have incorrectly written as if - as mentioned by #Shirkam)
String line;
int count=1;
do {
line = inFile.readLine();
if (line != null) {
outFile.println( count++ +"." + line);
}
} while (line != null);
inFile.close();
This works fine at my end.

Reading input from a file in Java

I am having the following file have 3 columns , i want read the following file and store them ArrayList , how to read it using Scanner or Buffer reader ?
For Example.
ArrayList<Integert>[][] M = new ArrayList[size][size]
M[1][859].add(1806476)
M[3][800].add(2131700)
M[3][800].add(2734107).. so one
A B C
1 859 [1806476]
3 800 "[2131700, 2734107, 2877209, 2877209]"
4 815 [2883211]
7 815 "[2429412, 2886810, 2886804]"
7 362 [2909301]
7 806 [89573]
7 853 [2182646]
8 800 "[2910937, 2836340, 2884417]"
Basically you want to store it in arrayList. You can use below approach
create a class of fields
class Multi {
int a, b, c;
}
public void addrecords(int i, int j, int k) {
Multi multi = new Multi();
Multi.a = i;
Multi.b = j;
Multi.c = k;
records.add(Multi);
}
List<Multi> records;
//code goes here
private static void parseInput(Map<Pair<Integer, Integer>, List<Integer>> data, String line) {
String[] tmp = line.split(" ");
String result = line.substring(tmp[0].length() + tmp[1].length() + 2);
result = result.replaceAll("\"", "");
result = result.replace(",", "");
result = result.replace("[", "");
result = result.replace("]", "");
List<Integer> t = new ArrayList<>();
for (String a: result.split(" "))
t.add(Integer.parseInt(a));
data.put(new Pair<>(Integer.parseInt(tmp[0]), Integer.parseInt(tmp[1])), t);
}
BufferedReader reader = null;
FileReader fileReader = null;
try {
fileReader = new FileReader("in.txt");
reader = new BufferedReader(fileReader);
String line;
Map<Pair<Integer, Integer>, List<Integer>> data = new HashMap<>();
while ((line = reader.readLine()) != null) {
parseInput(data, line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (reader != null)
reader.close();
if (fileReader != null)
fileReader.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
plus add try/catch block when u parse String to Integer

Java - Read large .txt data file in batch size of 10

I have a large data file say dataset.txt where data is in the format -
1683492079 kyra maharashtra 18/04/2017 10:16:17
1644073389 pam delhi 18/04/2017 10:16:17
.......
The fields are id, name, state, and timestamp.
I have around 50,000 lines of data in the .txt data file.
My requirement is to read the data from this data file in batch size of 10.
So in first batch I need to read from 0 to 9th elements. Next batch from 10th to 19th elements and so on...
Using BufferedReader I have managed to read the whole file:
import java.io.*;
public class ReadDataFile {
public static void main(String args[]) throws IOException {
BufferedReader br = new BufferedReader(new FileReader("dataset.txt"));
String line;
while((line = br.readLine())!= null)
{
System.out.println(line);
}
br.close();
}
}
But my requirement is to read the file in batch size of 10. I am new to Java so would really appreciate if some one can help me in simple terms.
As per #GhostCat answer - this what I have got -
public class ReadDataFile {
public static void main(String args[]) throws IOException {
BufferedReader br = new BufferedReader(new FileReader("dataSetExample.txt"));
readBatch(br,10);
}
public static void readBatch(BufferedReader reader, int batchSize) throws IOException {
List<String> result = new ArrayList<>();
for (int i = 0; i < batchSize; i++) {
String line = reader.readLine();
if (line != null) {
// result.add(line);
System.out.println(line);
}
}
// return result;
return ;
}
}
The file is read in the readBatch method so how do I know in the main method that the end of file is reached to call the next 10 records? Kindly help.
Your requirements aren't really clear; but something simple to get you started:
A) your main method shouldn't do any reading; it just prepare that BufferedReader object
B) you use that reader with a method like:
private static List<String> readBatch(Reader reader, int batchSize) throws IOException {
List<String> result = new ArrayList<>();
for (int i = 0; i < batchSize; i++) {
String line = reader.readLine();
if (line != null) {
result.add(line);
} else {
return result;
}
}
return result;
}
To be used in your main:
BufferedReader reader = ...
int batchSize = 10;
boolean moreLines = true;
while (moreLines) {
List<String> batch = readBatch(reader, batchSize);
... do something with that list
if (batch.size() < batchSize) {
moreLines = false;
}
This is meant as "suggestion" how you could approach this. Things missing from my answer: probably you should use a distinct class, and do parsing right there (and return a List<DataClass> instead of moving around those raw "line strings".
And of course: 50000 lines isn't really much of data. Unless we are talking an embedded device, there is really not much point regarding "batch style".
And finally: the term batch processing has a very distinct meaning; also in Java, and if you intend to go there, see here for further reading.
Anybody in need of working example ---
// Create a method to read lines (using buffreader) and should accept the batchsize as argument
private static List<String> readBatch(BufferedReader br, int batchSize) throws IOException {
// Create a List object which will contain your Batch Sized lines
List<String> result = new ArrayList<>();
for (int i = 1; i < batchSize; i++) { // loop thru all your lines
String line = br.readLine();
if (line != null) {
result.add(line); // add your lines to your (List) result
} else {
return result; // Return your (List) result
}
}
return result; // Return your (List) result
}
public static void main(String[] args) throws IOException {
//input file
BufferedReader br = new BufferedReader(new FileReader("c://ldap//buffreadstream2.csv"));
//output file
BufferedWriter bw = new BufferedWriter(new FileWriter("c://ldap//buffreadstream3.csv"));
// Your Batch size i.e. how many lines you want in your batch
int batchSize = 5; // Define your batchsize here
String line = null;
long batchNumber = 1;
try {
List<String> mylist = null;
while ((line = br.readLine()) != null) { // Do it for your all line in your csv file
bw.write("Batch Number # " + batchNumber + "\n");
System.out.println("Batch Number # " + batchNumber);
bw.write(line + "\n"); // Since br.readLine() reads the next line you have to catch your first line here itself
System.out.println(line); // else you will miss every batchsize number line
// process your First Line here...
mylist = readBatch(br, batchSize); // get/catch your (List) result here as returned from readBatch() method
for (int i = 0; i < mylist.size(); i++) {
System.out.println(mylist.get(i));
// process your lines here...
bw.write(mylist.get(i) + "\n"); // write/process your returned lines
}
batchNumber++;
}
System.out.println("Lines are Successfully copied!");
br.close(); // one you are done .. dont forget to close/flush
br = null; // all
bw.flush(); // your
bw.close(); // BR and
bw = null; // BWs..
} catch (Exception e) {
System.out.println("Exception caught: " + e.getMessage()); // Catch any exception here
}
}

How to create an file and copy the content from another file into the created file in java? [duplicate]

This question already has answers here:
Standard concise way to copy a file in Java?
(16 answers)
Closed 8 years ago.
I am trying to read a file and write to another file it is not working I invoke the method from the main
public boolean copy(String inputPlayList, String outputPlayList, int numberOfMunites)
{
String start1 = "#EXTINF:";
String afterNum = ";";
try
{
declaring those variable that I would use to pass the method
File fInput, fOutput;
String s;
String a;
assigning those variable to the method
fInput = new File(inputPlayList);
fOutput = new File(outputPlayList);
// Now I am using bufferedRead and BufferedWriter to read and write in a file
BufferedReader br = new BufferedReader(new FileReader(new File(inputPlayList)));
BufferedWriter out = new BufferedWriter(new BufferedWriter(new FileWriter(outputPlayList)));
// creating a while saying while the line is not finish contunue to read
while((s = br.readLine())!= null)
{
if(s.contains(start1)) {
String numberInString = s.substring(start1.length(), s.indexOf(afterNum));
numberOfMunites+= Integer.getInteger(numberInString);
}
// when it is finsh close the file.
out.write(s);
}
out.close();
System.out.println("donne");
}catch ( IOException e)
{
System.err.println("the is an erro that need to be fixed"+e);
}
return false;
}
}
Simplest way in java:
File input = new File("input/file");
File output = new File("output/file");
InputStream is = new FileInputStream(input); // can be any input stream, even url.open()
OutputStream os = new FileOutputStream(output);
byte[] buffer = new byte[4096];//
int read = 0;
while ((read = is.read(buffer)) != -1) {
os.write(buffer, 0, read);
}
is.close();
os.close();
Try Apache Commons IO Utils.
FileUtils.copyFile(new File(inputPlayList),new File(outputPlayList));
Here it is, but I don't understand the meaning of the numberOfminutes argument, what is it for? I've changed implementation to return calculated number of minutes from the function.
import java.io.*;
public class Main {
public static void main(String[] args) {
System.out.println(copy("D:\\1.txt", "D:\\2.txt", 0)); //returns the calculated number of minutes
}
public static int copy(String inputPlayList, String outputPlayList, int numberOfMinutes) {
String start1 = "#EXTINF:";
String afterNum = ";";
try {
BufferedReader br = new BufferedReader(new FileReader(new File(inputPlayList)));
PrintWriter out = new PrintWriter(new FileWriter(outputPlayList));
String s;
while ((s = br.readLine()) != null) {
if (s.contains(start1)) {
String numberInString = s.substring(start1.length(), s.indexOf(afterNum));
numberOfMinutes += Integer.parseInt(numberInString);
}
out.println(s);
}
out.close();
} catch (IOException e) {
System.err.println("Exception" + e);
}
return numberOfMinutes;
}
}

Code for reading from a text file doesn't work

I am new to Java and it has all been self-taught. I enjoy working with the code and it is just a hobby, so, I don't have any formal education on the topic.
I am at the point now where I am learning to read from a text file. The code that I have been given isn't correct. It works when I hardcode the exact number of lines but if I use a "for" loop to sense how many lines, it doesn't work.
I have altered it a bit from what I was given. Here is where I am now:
This is my main class
package textfiles;
import java.io.IOException;
public class FileData {
public static void main(String[] args) throws IOException {
String file_name = "C:/Users/Desktop/test.txt";
ReadFile file = new ReadFile(file_name);
String[] aryLines = file.OpenFile();
int nLines = file.readLines();
int i = 0;
for (i = 0; i < nLines; i++) {
System.out.println(aryLines[i]);
}
}
}
This is my class that will read the text file and sense the number of lines
package textfiles;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ReadFile {
private String path;
public ReadFile(String file_path) {
path = file_path;
}
int readLines() throws IOException {
FileReader file_to_read = new FileReader(path);
BufferedReader bf = new BufferedReader(file_to_read);
int numberOfLines = 0;
String aLine;
while ((aLine = bf.readLine()) != null) {
numberOfLines++;
}
bf.close();
return numberOfLines;
}
public String[] OpenFile() throws IOException {
FileReader fr = new FileReader(path);
BufferedReader textReader = new BufferedReader(fr);
int numberOfLines = 0;
String[] textData = new String[numberOfLines];
int i;
for (i = 0; i < numberOfLines; i++) {
textData[i] = textReader.readLine();
}
textReader.close();
return textData;
}
}
Please, keep in mind that I am self-taught; I may not indent correctly or I may make simple mistakes but don't be rude. Can someone look this over and see why it is not sensing the number of lines (int numberOfLines) and why it won't work unless I hardcode the number of lines in the readLines() method.
The problem is, you set the number of lines to read as zero with int numberOfLines = 0;
I'd rather suggest to use a list for the lines, and then convert it to an array.
public String[] OpenFile() throws IOException {
FileReader fr = new FileReader(path);
BufferedReader textReader = new BufferedReader(fr);
//int numberOfLines = 0; //this is not needed
List<String> textData = new ArrayList<String>(); //we don't know how many lines are there going to be in the file
//this part should work akin to the readLines part
String aLine;
while ((aLine = bf.readLine()) != null) {
textData.add(aLine); //add the line to the list
}
textReader.close();
return textData.toArray(new String[textData.size()]); //convert it to an array, and return
}
}
int numberOfLines = 0;
String[] textData = new String[numberOfLines];
textData is an empty array. The following for loop wont do anything.
Note also that this is not the best way to read a file line by line. Here is a proper example on how to get the lines from a text file:
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
ArrayList<String> list = new ArrayList<String>();
while ((line = br.readLine()) != null) {
list.add(line);
}
br.close();
I also suggest that you read tutorials on object oriented concepts.
This is a class that I wrote awhile back that I think you may find helpful.
public class FileIO {
static public String getContents(File aFile) {
StringBuilder contents = new StringBuilder();
try {
//use buffering, reading one line at a time
//FileReader always assumes default encoding is OK!
BufferedReader input = new BufferedReader(new FileReader(aFile));
try {
String line = null; //not declared within while loop
/*
* readLine is a bit quirky :
* it returns the content of a line MINUS the newline.
* it returns null only for the END of the stream.
* it returns an empty String if two newlines appear in a row.
*/
while ((line = input.readLine()) != null) {
contents.append(line);
contents.append(System.getProperty("line.separator"));
}
} finally {
input.close();
}
} catch (IOException ex) {
}
return contents.toString();
}
static public File OpenFile()
{
return (FileIO.FileDialog("Open"));
}
static private File FileDialog(String buttonText)
{
String defaultDirectory = System.getProperty("user.dir");
final JFileChooser jfc = new JFileChooser(defaultDirectory);
jfc.setMultiSelectionEnabled(false);
jfc.setApproveButtonText(buttonText);
if (jfc.showOpenDialog(jfc) != JFileChooser.APPROVE_OPTION)
{
return (null);
}
File file = jfc.getSelectedFile();
return (file);
}
}
It is used:
File file = FileIO.OpenFile();
It is designed specifically for reading in files and nothing else, so can hopefully be a useful example to look at in your learning.

Categories

Resources