I'm new to java. I'm required to read The input data(csv)(large number of records) I receive in the given below format:
A,1
A,2
B,3
B,4
C,5
C,6
A,7
A,8
B,9
B,10 ...
I'm using PrintWriter to write the data into the new CSV file. Is there a.ny way I can write into the new csv file this way from the above data? Here the condition is based on values A, B,C.
A,B,C
1,3,5
2,4,6
7,9
8,10...
I think this is possible if there are always A,B and C. But this idea can be extended to finite number of constants
What you can do is something like...
public void computeNewCSV() {
List<Integer> a = new LinkedList<Integer>();
List<Integer> b = new LinkedList<Integer>();
List<Integer> c = new LinkedList<Integer>();
FileInputStream fis = new FileInputStream("input_file");
BufferedReader br = new BufferedReader(new InputStreamReader(fis, Charset.forName("UTF-8")));
String line;
while ((line = br.readLine()) != null) {
String split[] = line.split(",");
if(split[0].equals("A") {
a.add(Integer.parseInt(split[1]));
} else if (split[0].equals("B") {
b.add(Integer.parseInt(split[1]));
} else if (split[0].equals("C") {
c.add(Integer.parseInt(split[1]));
}
}
br.close();
fis.close();
//Now you have the complete information to be put into the new file.
PrintWriter writer = new PrintWriter("output-file-name", "UTF-8");
writer.println("A,B,C");
while(!(a.isEmpty && b.isEmpty() && c.isEmpty())) {
StringBuilder sb = new StringBuilder("");
if(!a.isEmpty()) {
sb.append(a.remove(0));
}
sb.append(",");
if(!b.isEmpty()) {
sb.append(b.remove(0));
}
sb.append(",");
if(!c.isEmpty()) {
sb.append(c.remove(0));
}
writer.println(sb.toString());
}
writer.close();
}
Related
I've a little issue with my script function.
To set the context, I want to create a loop so that it modifies a text document little by little, in relation to what the user enters in the console.
My text document is written so that several "INSERT" entries are listed, and the user can replace them two by two with the text of his choice.
But the problem is the following: the String arraylist content remains empty, that logically causes an error on the 16th line, because there is a problem with the BufferedReader (the String line is systematically null, because of a Strem error).
How can I solve this ?
The code is the following :
public void script() {
while(index*5 <= array.size()) {
List<String> content = new ArrayList<>();
int modificater = 1;
int position = (((index-1)*5)+4);
FileInputStream fIS= new FileInputStream(file);
BufferedReader reader = new BufferedReader(new InputStreamReader(fIS, "UTF-8"));
String line = reader.readLine();
while(line != null) {
content.add(line);
line = reader.readLine();
}
System.out.println(content.get(position - 1));
Scanner enter = new Scanner(System.in);
String answer = enter.nextLine();
while(modificater < 3) {
for(String str : content) {
if(str.contains("INSERT")) {
str.replace("INSERT", answer);
modificater++;
}
}
}
reader.close();
FileWriter writer = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(writer);
for(String str : content) {
bw.write(str);
bw.newLine();
}
writer.close();
index++;
}
}
Here is an error that I have :
Exception in thread "main" java.io.IOException: Stream closed
at java.base/sun.nio.cs.StreamEncoder.ensureOpen(StreamEncoder.java:51)
at java.base/sun.nio.cs.StreamEncoder.write(StreamEncoder.java:124)
at java.base/java.io.OutputStreamWriter.write(OutputStreamWriter.java:208)
at java.base/java.io.BufferedWriter.flushBuffer(BufferedWriter.java:120)
at java.base/java.io.BufferedWriter.close(BufferedWriter.java:268)```
Try changing your reader below your writer.close() and close your bw.
public void script() {
while(index*5 <= array.size()) {
List<String> content = new ArrayList<>();
int modificater = 1;
int position = (((index-1)*5)+4);
FileInputStream fIS= new FileInputStream(file);
BufferedReader reader = new BufferedReader(new InputStreamReader(fIS, "UTF-8"));
String line = reader.readLine();
while(line != null) {
content.add(line);
line = reader.readLine();
}
System.out.println(content.get(position - 1));
Scanner enter = new Scanner(System.in);
String answer = enter.nextLine();
while(modificater < 3) {
for(String str : content) {
if(str.contains("INSERT")) {
str.replace("INSERT", answer);
modificater++;
}
}
}
FileWriter writer = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(writer);
for(String str : content) {
bw.write(str);
bw.newLine();
}
reader.close();
bw.close();
writer.close();
index++;
}
}
import java.util.*;
import java.io.*;
public class readFiles2 {
public static void main(String[] args) throws IOException{
// TODO Auto-generated method stub
BufferedReader reader = new BufferedReader(new FileReader("someFile.txt"));
try{
StringBuilder text = new StringBuilder();
String readStringLine = reader.readLine();
String[] lines= {};
for(int i = 0; readStringLine != null; i++){
readStringLine = reader.readLine();
//Trying to save seperate lines of text in an array.
lines[i] = readStringLine.toString();
}
}
finally{
reader.close();
}
}
So what I'm trying to do is save separate lines of strings from a .txt file to a String[] array. I'm kind of at a loss right now and don't really know what else I can do.
Since you don't know how many strings there are for your array, you might want to put the strings in a list and convert to an array at the end:
String readStringLine;
List<String> lines = new ArrayList<String>();
while((readStringLine = reader.readLine()) != null) {
lines.add(readStringLine);
}
String[] linesArray = lines.toArray(new String[lines.size()]);
Edit: Simpified to use a while loop to gather the line from the reader.
ArrayList<String> line = new ArrayList<>();
FileReader file = new FileReader(file.txt);
BufferedReader reader = new BufferedReader(file);
while (reader.ready()) {
line.add(reader.readLine());
reader.close();
file.close();
}
To acess, use line.get(i); where i>=0 and i<=array.size
Using autocloseable interface and Java 8 streams:
String [] stringsArray = null;
try(BufferedReader br = new BufferedReader(new FileReader("someFile.txt"))) {
List<String> strings = new ArrayList<>();
br.lines().forEach(c -> strings.add(c));
stringsArray = strings.toArray(new String[strings.size()]);
}
You need Java 8 to run this code
I'm trying to read a large text file in the form of:
datadfqsjmqfqs+dataqfsdqjsdgjheqf+qsdfklmhvqziolkdsfnqsdfmqdsnfqsdf+qsjfqsdfmsqdjkgfqdsfqdfsqdfqdfssdqdsfqdfsqdsfqdfsqdfs+qsfddkmgqjshfdfhsqdflmlkqsdfqdqdf+
I want to read this string in the text file as one big java String. Is this possible? I know the use of the split method.
It worked to read it line by line, but what I really need is to split this long text-string at the '+' sign. Afterwards I want to store it as an array, arraylist, list,...
Can anyone help me with this? Because every information on the internet is just about reading a file line by line.
Thanks in advance!
String inpStr = "datadfqsjmqfqs+dataqfsdqjsdgjheqf+qsdfklmhvqziolkdsfnqsdfmqdsnfqsdf+qsjfqsdfmsqdjkgfqdsfqdfsqdfqdfssdqdsfqdfsqdsfqdfsqdfs+qsfddkmgqjshfdfhsqdflmlkqsdfqdqdf+";
String[] inpStrArr = inpStr.split("+");
Hope this is what you need.
You can read file using BufferedReader or any IO-classes.suppose you have that String in testing.txt file then by reading each line from file you can split it by separator (+). and iterate over array and print.
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("C:\\testing.txt"));//file name with path
while ((sCurrentLine = br.readLine()) != null) {
String[] strArr = sCurrentLine.split("\\+");
for(String str:strArr){
System.out.println(str);
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
It seems to me like your problem is that you don't want to read the file line by line. So instead, try reading it in parts (say 20 characters each time and building your string):
char[] c = new char[20]; //best to save 20 as a final static somewhere
ArrayList<String> strings = new ArrayList<String>();
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(new FileReader(filename));
while (br.read(c) == 20) {
String str = new String(c);
if (str.contains("+") {
String[] parts = str.split("\\+");
sb.append(parts[0]);
strings.add(sb.toString());
//init new StringBuilder:
sb = new StringBuilder();
sb.add(parts[1]);
} else {
sb.append(str);
}
}
You should be able to get a String of length Integer.MAX_VALUE (always 2147483647 (231 - 1) by the Java specification, the maximum size of an array, which the String class uses for internal storage) or half your maximum heap size (since each character is two bytes), whichever is smaller
How many characters can a Java String have?
Try this one:
private static void readLongString(File file){
ArrayList<String> list = new ArrayList<String>();
StringBuilder builder = new StringBuilder();
int r;
try{
InputStream in = new FileInputStream(file);
Reader reader = new InputStreamReader(in);
while ((r = reader.read()) != -1) {
if(r=='+'){
list.add(builder.toString());
builder = new StringBuilder();
}
builder.append(r);
}
}catch (IOException ex){
ex.printStackTrace();
}
for(String a: list){
System.out.println(a);
}
}
Here is one way, caveat being you can't load more than the max int size (roughly one GB)
FileReader fr=null;
try {
File f=new File("your_file_path");
fr=new FileReader(f);
char[] chars=new char[(int)f.length()];
fr.read(chars);
String s=new String(chars);
//parse your string here
} catch (Exception e) {
e.printStackTrace();
}finally {
if(fr!=null){
try {
fr.close();
} catch (IOException e) {
}
}
}
I want to read in a file and create a duplicate of the file but my code only write the last line in the file. How do I make so that whenever I call write(), it writes to a new line. I want to create a new file for the duplicate so I can't add true to FileWriter constructor.
This is my code:
//Create file reader
BufferedReader iReader = new BufferedReader(new FileReader(args[1]));
//Create file writer
BufferedWriter oWriter = new BufferedWriter(new FileWriter(args[2], true));
String strLine;
//reading file
int iterate = 0;
while((strLine = iReader.readLine()) != null) {
instructions[iterate] = strLine;
}
//creating duplicate
for(int i = 0; i < instructions.length; i++) {
if(instructions[i] != null) {
oWriter.write(instructions[i]);
oWriter.newLine();
} else {
break;
}
}
try {
iReader.close();
oWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
You are not incrementing iterate
int iterate = 0;
while((strLine = iReader.readLine()) != null)
{
instructions[iterate] = strLine;
iterate++;
}
You're not updating the index of the instructions array.
In addition, it's not immediately clear why you're copying the file this way anyway; why bother doing it line-by-line? Or just use a utility class, like from Apache Commons.
Lets say I have a text file called: data.txt (contains 2000 lines)
How do I read given specific line from: 500-1500 and then 1500-2000
and display the output of specific line?
this code will read whole files (2000 line)
public static String getContents(File aFile) {
StringBuffer contents = new StringBuffer();
try {
BufferedReader input = new BufferedReader(new FileReader(aFile));
try {
String line = null;
while (( line = input.readLine()) != null){
contents.append(line);
contents.append(System.getProperty("line.separator"));
}
}
finally {
input.close();
}
}
catch (IOException ex){
ex.printStackTrace();
}
return contents.toString();
}
How do I modify above code to read specific line?
I suggest java.io.LineNumberReader. It extends BufferedReader and
you can use its LineNumberReader.getLineNumber(); to get the current line number
You can also use Java 7 java.nio.file.Files.readAllLines which returns a List<String> if it suits you better
Note:
1) favour StringBuilder over StringBuffer, StringBuffer is just a legacy class
2) contents.append(System.getProperty("line.separator")) does not look nice
use contents.append(File.separator) instead
3) Catching exception seems irrelevant, I would also suggest to change your code as
public static String getContents(File aFile) throws IOException {
BufferedReader rdr = new BufferedReader(new FileReader("aFile"));
try {
StringBuilder sb = new StringBuilder();
// read your lines
return sb.toString();
} finally {
rdr.close();
}
}
now code looks cleaner in my view. And if you are in Java 7 use try-with-resources
try (BufferedReader rdr = new BufferedReader(new FileReader("aFile"))) {
StringBuilder sb = new StringBuilder();
// read your lines
return sb.toString();
}
so finally your code could look like
public static String[] getContents(File aFile) throws IOException {
try (LineNumberReader rdr = new LineNumberReader(new FileReader(aFile))) {
StringBuilder sb1 = new StringBuilder();
StringBuilder sb2 = new StringBuilder();
for (String line = null; (line = rdr.readLine()) != null;) {
if (rdr.getLineNumber() >= 1500) {
sb2.append(line).append(File.pathSeparatorChar);
} else if (rdr.getLineNumber() > 500) {
sb1.append(line).append(File.pathSeparatorChar);
}
}
return new String[] { sb1.toString(), sb2.toString() };
}
}
Note that it returns 2 strings 500-1499 and 1500-2000
A slightly more cleaner solution would be to use FileUtils in apache commons.
http://commons.apache.org/io/api-release/org/apache/commons/io/FileUtils.html
Example snippet:
String line = FileUtils.readLines(aFile).get(lineNumber);
The better way is to use BufferedReader. If you want to read line 32 for example:
for(int x = 0; x < 32; x++){
buf.readLine();
}
lineThreeTwo = buf.readLine();
Now in String lineThreeTwo you have stored line 32.