Reading numbers from a file and creating an array (java) - java

I cannot figure out how to make this txt file with numbers into an array, I am able to get it to read and print the screen but I need to be able to organize the numbers and delete the duplicates. This is what my code looks like so far
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class File {
public static void main(String[] args) {
String filename = "C:/input.txt";
File rfe = new File();
rfe.readFile(filename);
}
private void readFile(String name) {
String input;
try (BufferedReader reader = new BufferedReader(new FileReader(name))) {
while((input = reader.readLine()) != null) {
System.out.format(input); // Display the line on the monitor
}
}
catch(FileNotFoundException fnfe) {
}
catch(IOException ioe) {
}
catch(Exception ex) { // Not required, but a good practice
}
}
}

I would recommend using an ArrayList rather than an Array.
With an array you would have to parse through the list and calculate the line count before you could even initialize it. An ArrayList is much more flexible as you don't have to declare how many values will be added to it.
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class File {
private List<Integer> data = new ArrayList<Integer>(); //Create ArrayList
public static void main(String[] args) {
String filename = "C:/input.txt";
File rfe = new File();
rfe.readFile(filename);
}
private void readFile(String name) {
String input;
try (BufferedReader reader = new BufferedReader(new FileReader(name))) {
while((input = reader.readLine()) != null) {
data.add(Integer.parseInt(input));//Add each parsed number to the arraylist
System.out.println(input); // Display the line on the monitor
}
}
catch(FileNotFoundException fnfe) {
}
catch(IOException ioe) {
}
catch(Exception ex) { // Not required, but a good practice
ex.printstacktrace(); //Usually good for general handling
}
}
}

Related

Could it not delete the entire file content while saving into file? Java [duplicate]

This question already has answers here:
PrintWriter append method not appending
(5 answers)
Closed 4 years ago.
I've recently made a Snake game with function that allows to store and find the best score of his. But unfortunetely it every time it saves your score into file, it deletes the previous file content. Is there any way to avoid that? As it is visible in the code below, I've made 3 methods. The first one is to save your score into a file. Last ones are to find the best score.
package matajus.snake;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class Score {
private File file;
public static int score;
private static final String fileName = "BestScores.txt";
public Score() {
file = new File(fileName);
if(!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void saveToFile() throws FileNotFoundException {
PrintWriter print = new PrintWriter(fileName);
print.println(score);
print.close();
}
public int findBestScore() {
List<Integer> lines = new ArrayList<Integer>();
Scanner input;
int bestScore = 0;
try {
input = new Scanner(file);
if(linesNumber() > 0) {
for(int i = 0; i < linesNumber(); i++) {
String readLine = input.nextLine();
int line = Integer.parseInt(readLine);
lines.add(line);
}
bestScore = Collections.max(lines);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return bestScore;
}
private int linesNumber() throws FileNotFoundException {
BufferedReader reader = new BufferedReader(new FileReader(fileName));
String line;
int lines = 0;
try {
while((line = reader.readLine()) != null) {
lines++;
}
} catch (Exception e) {
e.printStackTrace();
}
return lines;
}
}
PrintWritter will truncate the file: https://docs.oracle.com/javase/7/docs/api/java/io/PrintWriter.html#PrintWriter(java.lang.String)
Have a look at the proposed solution here: How to append text to an existing file in Java

Print all content from multiple files in directory

I have the following code seen below, this code looks through a directory and then prints all of the different file names. Now my question is, how would I go about changing my code, so that it would also print out all of the content within the files which it finds/prints? As an example, lets say the code finds 3 files in the directory, then it would print out all the content within those 3 files.
import java.io.File;
import java.io.IOException;
public class EScan {
static String usernamePc = System.getProperty("user.name");
final static File foldersPc = new File("/Users/" + usernamePc + "/Library/Mail/V2");
public static void main(String[] args) throws IOException {
listFilesForFolder(foldersPc);
}
public static void listFilesForFolder(final File foldersPc) throws IOException {
for (final File fileEntry : foldersPc.listFiles()) {
if (fileEntry.isDirectory()) {
listFilesForFolder(fileEntry);
} else {
System.out.println(fileEntry.getName());
}
}
}
}
I tested it before posting. it is working.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* #author EdwinAdeola
*/
public class TestPrintAllFiles {
public static void main(String[] args) {
//Accessing the folder path
File myFolder = new File("C:\\Intel");
File[] listOfFiles = myFolder.listFiles();
String fileName, line = null;
BufferedReader br;
//For each loop to print the content of each file
for (File eachFile : listOfFiles) {
if (eachFile.isFile()) {
try {
//System.out.println(eachFile.getName());
fileName = eachFile.getAbsolutePath();
br = new BufferedReader(new FileReader(fileName));
try {
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException ex) {
Logger.getLogger(TestPrintAllFiles.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (FileNotFoundException ex) {
Logger.getLogger(TestPrintAllFiles.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
}
You may use Scanner to read the contents of the file
try {
Scanner sc = new Scanner(fileEntry);
while (sc.hasNextLine()) {
String s = sc.nextLine();
System.out.println(s);
}
sc.close();
} catch (Exception e) {
e.printStackTrace();
}
You can try one more way if you find suitable :
package com.grs.stackOverFlow.pack10;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Arrays;
import java.util.List;
public class EScan {
public static void main(String[] args) throws IOException {
File dir=new File("C:/your drive/");
List<File> files = Arrays.asList(dir.listFiles(f->f.isFile()));
//if you want you can filter files like f->f.getName().endsWtih(".csv")
for(File f: files){
List<String> lines = Files.readAllLines(f.toPath(),Charset.defaultCharset());
//processing line
lines.forEach(System.out::println);
}
}
}
Above code can me exploited in number of ways like processing line can be modified to add quotes around lines as below:
lines.stream().map(t-> "'" + t+"'").forEach(System.out::println);
Or print only error messages lines
lines.stream().filter(l->l.contains("error")).forEach(System.out::println);
Above codes and variations are tested.

How can i remove a word/line and replace it with a new one in a txt file (Java)?

For example we have a .txt file:
Name smth
Year 2012
Copies 1
And I want to replace it with that:
Name smth
Year 2012
Copies 0
Using java.io.*.
Here is the code that does that. Let me know if you have any question.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.LinkedHashMap;
import java.util.Map;
public class Test2 {
Map<String, String> someDataStructure = new LinkedHashMap<String, String>();
File fileDir = new File("c:\\temp\\test.txt");
public static void main(String[] args) {
Test2 test = new Test2();
try {
test.readFileIntoADataStructure();
test.writeFileFromADataStructure();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
private void readFileIntoADataStructure() throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(
new FileInputStream(fileDir)));
String line;
while ((line = in.readLine()) != null) {
if (line != null && !line.trim().isEmpty()) {
String[] keyValue = line.split(" ");
// Do you own index and null checks here this is just a sample
someDataStructure.put(keyValue[0], keyValue[1]);
}
}
in.close();
}
private void writeFileFromADataStructure() throws IOException {
Writer out = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(fileDir)));
for (String key : someDataStructure.keySet()) {
// Apply whatever business logic you want to apply here
myBusinessMethod(key);
out.write(key + " " + someDataStructure.get(key) + "\n");
out.append("\r\n");
out.append("\r\n");
}
out.flush();
out.close();
}
private String myBusinessMethod(String data) {
if (data.equalsIgnoreCase("Copies")) {
someDataStructure.put(data, "0");
}
return data;
}
}
Read your original text file line by line and separate them into string tokens delimited by spaces for output, then when the part you want replaced is found (as a string), replace the output to what you want it to be. Adding the false flag to the filewrite object ("filename.txt", false) will overwrite and not append to the file allowing you to replace the contents of the file.
this is the code to do that
try {
String sCurrentLine;
BufferedReader br = new BufferedReader(new FileReader("yourFolder/theinputfile.txt"));
BufferedWriter bw = new BufferedWriter(new FileWriter("yourFolder/theinputfile.txt" , false));
while ((sCurrentLine = br.readLine()) != null) {
if(sCurrentLine.indexOf("Copies")>=0){
bw.write("Copies 0")
}
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close()bw.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
hopefully that help

null pointer exception in reading tsv file

hi can anybody help me with below code. why this is throwing null pointer exception and how i can avoid it.
i am trying to read a tsv file and csv file and do some processing with this.
when i am calling getDictionaryValues function it throwing null pointer exception.
package com.ugam.qa.tittle;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class TittleMatch {
private static TittleMatchUtil tMU;
public static void main(String[] args) {
String fullname="d:/files/listing/Headphones.tsv";
Set<String> attributeSet=new HashSet<String>();
attributeSet.add("Storage Type");
attributeSet.add("Recording Definition");
attributeSet.add("Type");
attributeSet.add("Brand");
BufferedReader in = null;
try
{
System.out.println("file found");
in= new BufferedReader(new FileReader(fullname));
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
String str;
String prv_Pid="-1";
try {
str = in.readLine();
while ((str = in.readLine()) != null) {
if (str.trim().length() == 0 ) {
System.out.println("while loop");
continue;}
String[] values = str.split("\\t");
//System.out.println(values.length);
if(prv_Pid=="-1" || values[9]==prv_Pid)
{
if(attributeSet.contains(values[12]))
{
ArrayList<Set<String>> dicValues=new ArrayList<Set<String>>();
if(values[12]!=null && values[13]!=null)
{
dicValues=tMU.getDictionaryValues(values[12],values[13]);
}
//Set<String> tittle=new HashSet<String>();
//tittle.add(values[8]);
//System.out.println(tittle);
}
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Obviously this variable is evaluated to null, since you never assign a value to it.
private static TittleMatchUtil tMU;
One solution would be assigning a new TittleMatchUtil object to the variable:
private static TittleMatchUtil tMU = new TittleMatchUtil();
and another one is to make the getDictionaryValues() method static, which I wouldn't do, because it may require more code re-factoring.

Correct syntax for inputing a String file into a 2D Array?

What is the correct syntax for creating a 2D array from a text file? This array must be string not char or int. None of the information I've found on this is for string, and I haven't been able to figure the exact syntax out myself.
You can use ArrayList object .Its internal implemetation is Resizable or growable array.
So you can achieve your requirement by ArrayList<String>.You can get even arry by using its utility methods.
For more details ArrayList docs
For sample click here
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class Read2DimensionFileToList {
public static void main(String[] args) {
String [][] sList=new String[100][2];
BufferedReader br = null;
try {
String s;
br = new BufferedReader(new FileReader("C:\\testing.txt"));
int i=0;
while ((s = br.readLine()) != null) {
String []sArray=s.split(",");
sList[i++][0]=sArray[0];
sList[i][1]=sArray[1];
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}

Categories