This question already has answers here:
Java: Reading a file into an array
(5 answers)
Closed 1 year ago.
I have a text file like this :
abc def jhi
klm nop qrs
tuv wxy zzz
I want to have a string array like :
String[] arr = {"abc def jhi","klm nop qrs","tuv wxy zzz"}
I've tried :
try
{
FileInputStream fstream_school = new FileInputStream("text1.txt");
DataInputStream data_input = new DataInputStream(fstream_school);
BufferedReader buffer = new BufferedReader(new InputStreamReader(data_input));
String str_line;
while ((str_line = buffer.readLine()) != null)
{
str_line = str_line.trim();
if ((str_line.length()!=0))
{
String[] itemsSchool = str_line.split("\t");
}
}
}
catch (Exception e)
{
// Catch exception if any
System.err.println("Error: " + e.getMessage());
}
Anyone help me please....
All answer would be appreciated...
If you use Java 7 it can be done in two lines thanks to the Files#readAllLines method:
List<String> lines = Files.readAllLines(yourFile, charset);
String[] arr = lines.toArray(new String[lines.size()]);
Use a BufferedReader to read the file, read each line using readLine as strings, and put them in an ArrayList on which you call toArray at end of loop.
Based on your input you are almost there. You missed the point in your loop where to keep each line read from the file. As you don't a priori know the total lines in the file, use a collection (dynamically allocated size) to get all the contents and then convert it to an array of String (as this is your desired output).
Something like this:
String[] arr= null;
List<String> itemsSchool = new ArrayList<String>();
try
{
FileInputStream fstream_school = new FileInputStream("text1.txt");
DataInputStream data_input = new DataInputStream(fstream_school);
BufferedReader buffer = new BufferedReader(new InputStreamReader(data_input));
String str_line;
while ((str_line = buffer.readLine()) != null)
{
str_line = str_line.trim();
if ((str_line.length()!=0))
{
itemsSchool.add(str_line);
}
}
arr = (String[])itemsSchool.toArray(new String[itemsSchool.size()]);
}
Then the output (arr) would be:
{"abc def jhi","klm nop qrs","tuv wxy zzz"}
This is not the optimal solution. Other more clever answers have already be given. This is only a solution for your current approach.
This is my code to generate random emails creating an array from a text file.
import java.io.*;
public class Generator {
public static void main(String[]args){
try {
long start = System.currentTimeMillis();
String[] firstNames = new String[4945];
String[] lastNames = new String[88799];
String[] emailProvider ={"google.com","yahoo.com","hotmail.com","onet.pl","outlook.com","aol.mail","proton.mail","icloud.com"};
String firstName;
String lastName;
int counter0 = 0;
int counter1 = 0;
int generate = 1000000;//number of emails to generate
BufferedReader firstReader = new BufferedReader(new FileReader("firstNames.txt"));
BufferedReader lastReader = new BufferedReader(new FileReader("lastNames.txt"));
PrintWriter write = new PrintWriter(new FileWriter("emails.txt", false));
while ((firstName = firstReader.readLine()) != null) {
firstName = firstName.toLowerCase();
firstNames[counter0] = firstName;
counter0++;
}
while((lastName= lastReader.readLine()) !=null){
lastName = lastName.toLowerCase();
lastNames[counter1]=lastName;
counter1++;
}
for(int i=0;i<generate;i++) {
write.println(firstNames[(int)(Math.random()*4945)]
+'.'+lastNames[(int)(Math.random()*88799)]+'#'+emailProvider[(int)(Math.random()*emailProvider.length)]);
}
write.close();
long end = System.currentTimeMillis();
long time = end-start;
System.out.println("it took "+time+"ms to generate "+generate+" unique emails");
}
catch(IOException ex){
System.out.println("Wrong input");
}
}
}
You can read file line by line using some input stream or scanner and than store that line in String Array.. A sample code will be..
File file = new File("data.txt");
try {
//
// Create a new Scanner object which will read the data
// from the file passed in. To check if there are more
// line to read from it we check by calling the
// scanner.hasNextLine() method. We then read line one
// by one till all line is read.
//
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
//store this line to string [] here
System.out.println(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Scanner scanner = new Scanner(InputStream);//Get File Input stream here
StringBuilder builder = new StringBuilder();
while (scanner.hasNextLine()) {
builder.append(scanner.nextLine());
builder.append(" ");//Additional empty space needs to be added
}
String strings[] = builder.toString().split(" ");
System.out.println(Arrays.toString(strings));
Output :
[abc, def, jhi, klm, nop, qrs, tuv, wxy, zzz]
You can read more about scanner here
You can use the readLine function to read the lines in a file and add it to the array.
Example :
File file = new File("abc.txt");
FileInputStream fin = new FileInputStream(file);
BufferedReader reader = new BufferedReader(fin);
List<String> list = new ArrayList<String>();
while((String str = reader.readLine())!=null){
list.add(str);
}
//convert the list to String array
String[] strArr = Arrays.toArray(list);
The above array contains your required output.
Related
I tried concatenating 2 lines of text in a given text file and printing the output to the console. My code is very complicated, is there a simpler method to achieve this by using FileHandling basic concepts ?
import java.io.*;
public class ConcatText{
public static void main(String[] args){
BufferedReader br = null;
try{
String currentLine;
br = new BufferedReader(new FileReader("C:\\Users\\123\\Documents\\CS105\\FileHandling\\concat.file.text"));
StringBuffer text1 = new StringBuffer (br.readLine());
StringBuffer text2 = new StringBuffer(br.readLine());
text1.append(text2);
String str = text1.toString();
str = str.trim();
String array[] = str.split(" ");
StringBuffer result = new StringBuffer();
for(int i=0; i<array.length; i++) {
result.append(array[i]);
}
System.out.println(result);
}
catch(IOException e){
e.printStackTrace();
}finally{
try{
if(br != null){
br.close();
}
}catch(IOException e){
e.printStackTrace();
}
}
}
}
The text file is as follows :
GTAGCTAGCTAGC
AGCCACGTA
the output should be as follows (concatenation of the text file Strings) :
GTAGCTAGCTAGCAGCCACGTA
If you are using java 8 or newer, the simplest way would be:
List<String> lines = Files.readAllLines(Paths.get(filePath));
String result = String.join("", lines);
If you are using java 7, at least you can use try with resources to reduce the clutter in the code, like this:
try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
StringBuffer text1 = new StringBuffer (br.readLine());
StringBuffer text2 = new StringBuffer(br.readLine());
// ...
}catch(IOException e){
e.printStackTrace();
}
This way, resources will be autoclosed and you don't need to call br.close().
Short answer, there is:
public static void main(String[] args) {
//this is called try-with-resources, it handles closing the resources for you
try (BufferedReader reader = new BufferedReader(...)) {
StringBuilder stringBuilder = new StringBuilder();
String line = reader.readLine();
//readLine() will return null when there are no more lines
while (line != null) {
//replace any spaces with empty string
//first argument is regex matching any empty spaces, second is replacement
line = line.replaceAll("\\s+", "");
//append the current line
stringBuilder.append(line);
//read the next line, will be null when there are no more
line = reader.readLine();
}
System.out.println(stringBuilder);
} catch (IOException exc) {
exc.printStackTrace();
}
}
First of all read on try with resources, when you are using it you don't need to close manually resources(files, streams, etc.), it will do it for you. This for example.
You don't need to wrap read lines in StringBuffer, you don't get anything out of it in this case.
Also read about the methods provided by String class starting with the java doc - documentation.
I am new to java and working on file operations. I have this input and modify text files as follows:
input.txt: contains id,firstname,lastname
1000:Mark,Peters,3.9
modify.txt: contains id,oldvalue:newvalue
1000,Mark:John
I am supposed to search the id and make the updations accordingly. So in modify.txt file I have an id and old value which is to be replaced with new value in the input.txt
So after modification, my input.txt line output should be printed as:
1000:John,Peters,3.9
I have written the following code, but I am not sure how to proceed with updations. However, I have managed to read the files and split it and get the id.
public static void main(String[] args) {
try {
BufferedReader file1 = new BufferedReader(new FileReader(new File("src/input.txt")));
BufferedReader file2 = new BufferedReader(new FileReader(new File("src/modify.txt")));
String str1 = file1.readLine();
String input[] = str1.split(":");
int id1 = Integer.parseInt(input[0]);
System.out.println(str1);
System.out.println(id1);
String str2 = file2.readLine();
String modify[] = str2.split(",");
int id2 = Integer.parseInt(modify[0]);
System.out.println(str2);
System.out.println(id2);
file1.close();
file2.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Can anyone help me with this? Thanks. Appreciate your help.
You can read the line in modify.txt file and split the line using regex [,:]. It will split the line into separate parts like id, firstName and lastName etc.
After read the each line in input.txt file and and split the each line using the regex [,:]. And compare the first element in the list with element in the list created from modify.txt file. if the element is equals replace the line with the new data from list created from modify.txt file.
public static void main(String[] args) {
try {
BufferedReader f1 = new BufferedReader(new FileReader(new File("src/input.txt")));
BufferedReader f2 = new BufferedReader(new FileReader(new File("src/modify.txt")));
String regex = "[,:]";
StringBuffer inputBuffer = new StringBuffer();
String line;
String[] newLine = f2.readLine().split(regex);
while ((line = f1.readLine()) != null) {
String[] data = line.split(regex);
if (data[0].equals(newLine[0])) {
line = line.replace(newLine[1], newLine[2]);
}
inputBuffer.append(line);
inputBuffer.append(System.lineSeparator());
}
f1.close();
f2.close();
FileOutputStream fileOut = new FileOutputStream("src/input.txt");
fileOut.write(inputBuffer.toString().getBytes());
fileOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
I'm having trouble scanning a given file for certain words and assigning them to variables, so far I've chosen to use Scanner over BufferedReader because It's more familiar. I'm given a text file and this particular part I'm trying to read the first two words of each line (potentially unlimited lines) and maybe add them to an array of sorts. This is what I have:
File file = new File("example.txt");
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
String line = sc.nextLine();
String[] ary = line.split(",");
I know It' a fair distance off, however I'm new to coding and cannot get past this wall...
An example input would be...
ExampleA ExampleAA, <other items seperated by ",">
ExampleB ExampleBB, <other items spereated by ",">
...
and the proposed output
VariableA = ExampleA ExampleAA
VariableB = ExampleB ExampleBB
...
You can try something like this
File file = new File("D:\\test.txt");
Scanner sc = new Scanner(file);
List<String> list =new ArrayList<>();
int i=0;
while (sc.hasNextLine()) {
list.add(sc.nextLine().split(",",2)[0]);
i++;
}
char point='A';
for(String str:list){
System.out.println("Variable"+point+" = "+str);
point++;
}
My input:
ExampleA ExampleAA, <other items seperated by ",">
ExampleB ExampleBB, <other items spereated by ",">
Out put:
VariableA = ExampleA ExampleAA
VariableB = ExampleB ExampleBB
To rephrase, you are looking to read the first 2 words of a line (everything before the first comma) and store it in a variable to process further.
To do so, your current code looks fine, however, when you grab the line's data, use the substring function in conjunction with indexOf to just get the first part of the String before the comma. After that, you can do whatever processing you want to do with it.
In your current code, ary[0] should give you the first 2 words.
public static void main(String[] args)
{
File file = new File("example.txt");
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String line = "";
List l = new ArrayList();
while ((line = br.readLine()) != null) {
System.out.println(line);
line = line.trim(); // remove unwanted characters at the end of line
String[] arr = line.split(",");
String[] ary = arr[0].split(" ");
String firstTwoWords[] = new String[2];
firstTwoWords[0] = ary[0];
firstTwoWords[1] = ary[1];
l.add(firstTwoWords);
}
Iterator it = l.iterator();
while (it.hasNext()) {
String firstTwoWords[] = (String[]) it.next();
System.out.println(firstTwoWords[0] + " " + firstTwoWords[1]);
}
}
I need help trying to read two files that have the census from 2010 and 2000. I have to read both files and then find out the population growth between those two files. I keep getting null for ever single state. I know that I have null for inLine1 and inLine2.
The file looks like this
Alabama,4779736
Alaska,710231
Arizona,6392017
Arkansas,2915918
Code:
import java.util.ArrayList;
import java.util.Scanner;
import java.io.*;
public class pa10
{
public static void main(String[] args, char[] inLine2, char[] inLine1)
throws java.io.IOException
{
String fileName1 = "Census2000growth.txt";
String fileName2 = "Census2010growth.txt";
int i;
File f = new File("Census2010growth.txt");
if(!f.exists()) {
System.out.println( "file does not exist ");
}
Scanner infile = new Scanner(f);
infile.useDelimiter ("[\t|,|\n|\r]+"); //create a delimiter
final int MAX = 51;
int [] myarray = new int [MAX];
String[] statearray = new String[MAX];
int fillsize;
// set up input stream1
FileReader fr1 = new
FileReader(fileName1);
// buffer the input stream
BufferedReader br1 =
new BufferedReader(fr1);
// set up input stream2
FileReader fr2 = new
FileReader(fileName2);
// buffer the input stream
BufferedReader br2 =
new BufferedReader(fr2);
// read and display1
String buffer1 = "";
ArrayList<String> firstFile1 = new ArrayList<String>();
while ((buffer1 = br1.readLine()) != null) {
firstFile1.add(buffer1);
System.out.println(inLine1); // display the line
}
br1.close();
//Now read the second file or make for this separate method
// read and display2
String buffer2 = "";
ArrayList<String> firstFile2 = new ArrayList<String>();
while ((buffer2 = br2.readLine()) != null) {
firstFile2.add(buffer2);
System.out.println(inLine2); // display the line
}
br2.close();
//Read all the lines in array or list
//After that you can calculate them.
}
}
Read the BufferedReader documentation. Your file isn't formatted with the types of line separators it is expecting. I suggest using a Scanner and setting the line separator to the appropriate pattern, or using String.split
You have two different variables, buffer1 and inline1. Since you never set the value of inline1, it will always be null.
I am trying to read from a file to an array. I tried two different styles and both aren't working. Below are the two styles.
Style 1
public class FileRead {
int i;
String a[] = new String[2];
public void read() throws FileNotFoundException {
//Z means: "The end of the input but for the final terminator, if any"
a[i] = new Scanner(new File("C:\\Users\\nnanna\\Documents\\login.txt")).useDelimiter("\\n").next();
for(i=0; i<=a.length; i++){
System.out.println("" + a[i]);
}
}
public static void main(String args[]) throws FileNotFoundException{
new FileRead().read();
}
}
Style 2
public class FileReadExample {
private int j = 0;
String path = null;
public void fileRead(File file){
StringBuilder attachPhoneNumber = new StringBuilder();
try{
FileReader read = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(read);
while((path = bufferedReader.readLine()) != null){
String a[] = new String[3];
a[j] = path;
j++;
System.out.println(path);
System.out.println(a[j]);
}
bufferedReader.close();
}catch(IOException exception){
exception.printStackTrace();
}
}
I need it to read each line of string and store each line in an array. But neither works. How do I go about it?
Do yourself a favor and use a library that provides this functionality for you, e.g.
Guava:
// one String per File
String data = Files.toString(file, Charsets.UTF_8);
// or one String per Line
List<String> data = Files.readLines(file, Charsets.UTF_8);
Commons / IO:
// one String per File
String data = FileUtils.readFileToString(file, "UTF-8");
// or one String per Line
List<String> data = FileUtils.readLines(file, "UTF-8");
It's not really clear exactly what you're trying to do (partly with quite a lot of code commented out, leaving other code which won't even compile), but I'd recommend you look at using Guava:
List<String> lines = Files.readLines(file, Charsets.UTF_8);
That way you don't need to mess around with the file handling yourself at all.