I've a text file which contains text as:
VOLT=367
CURRENT=0.07
TEMP=031
RPM=3780
63HZ
VOLT=288
CURRENT=0.00
TEMP=030
RPM=3420
57HZ
and so on....
I want to take this text file as input in java and create an output text file having this text arranged as:
367,0.07,031,3780,63
288,0.00,030,3420,57
and so on until the end of txt file..
Coding attempt so far:
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
try {
FileInputStream fstream = new FileInputStream("file path\data.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
BufferedWriter brw = new BufferedWriter(new OutputStreamWriter(out));
do {
for (int i=1;i<50;i++) {
//I dont know what to do here
...
Try this,
String input = "";
br = new BufferedReader(new FileReader(inputFile));
out = new PrintWriter(outputFile);
StringBuilder result = new StringBuilder();
while ((input = br.readLine()) != null)
{
if(input.contains("HZ"))
{
result.append(input.replace("HZ", ""));
result.append("\n");
}
else
{
result.append(input.substring(input.indexOf("=") + 1, input.length()));
result.append(",");
}
}
System.out.println("result : "+result.toString());
Use this simple code.
String res="";
while ((input = br.readLine()) != null)
{
if(input.indexOf("=")!= -1){
res+=input.split("=+")[1]+",";
}
else{
res+="\n";
}
}
System.out.println("result : "+res.substring(0,res.length()-1));//To omit last ','
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++;
}
}
I have a text file with letters up and I want to make them lower letters. It is the code but it becomes only the last line
BufferedReader in = new BufferedReader(new FileReader("C:\Users\xxx\Desktop\j.txt"));
String line;
while((line = in.readLine()) != null)
{
blig=line.toUpperCase();
}
try (BufferedWriter writer = new BufferedWriter(new FileWriter("C:\Users\xxx\Desktop\j.txt"))) {
writer.write(blig);
}
You are traversing through the whole file but just storing the last line. In order to get all the lines, you need to store all the lines you are reading, convert them to uppercase, then write them back to the file:
List<String> upper = new ArrayList<>();
try(BufferedReader in = new BufferedReader(new FileReader("C:\Users\xxx\Desktop\j.txt")))
{
String line;
while((line = in.readLine()) != null)
{
// upper.add(line.toUpperCase()); // if you need upper case
upper.add(line.toLowerCase()); // if you need lower case
}
}
try(BufferedWriter writer = new BufferedWriter(new FileWriter("C:\Users\xxx\Desktop\j.txt")))
{
for(String str : upper)
{
writer.write(str);
writer.newLine(); // remove if not needed.
}
}
BufferedReader in = new BufferedReader(new FileReader("C:\Users\xxx\Desktop\j.txt"));
BufferedWriter writer = new BufferedWriter(new FileWriter("C:\Users\xxx\Desktop\lowerJ.txt"));
String line;
while((line = in.readLine()) != null) {
writer.write(line.toLowerCase());
}
If you are trying to lower the case of characters, then why use to Uper?
blig=line.toUpperCase();
It sould be bling=line.toLowerCase();
Because you are writing only the last line while you are not concatenating all the result.
replace the while statement by
blig += line.toUpperCase() + "\\n";
I have some CSV file with the same column header.
I want to make them to one file.So I found something similar to me. Link is Merge CSV files into a single file with no repeated headers.
but I want to return the data as a String, but this code has no return.
I try to modify that. but I failed.
I want to put the data from several csv into one variable.
String[] headers = null;
String firstFile = "/path/to/firstFile.dat";
Scanner scanner = new Scanner(new File(firstFile));
if (scanner.hasNextLine())
headers[] = scanner.nextLine().split(",");
scanner.close();
Iterator<File> iterFiles = listOfFilesToBeMerged.iterator();
BufferedWriter writer = new BufferedWriter(new FileWriter(firstFile, true));
while (iterFiles.hasNext()) {
File nextFile = iterFiles.next();
BufferedReader reader = new BufferedReader(new FileReader(nextFile));
String line = null;
String[] firstLine = null;
if ((line = reader.readLine()) != null)
firstLine = line.split(",");
if (!Arrays.equals (headers, firstLine))
throw new FileMergeException("Header mis-match between CSV files: '" +
firstFile + "' and '" + nextFile.getAbsolutePath());
while ((line = reader.readLine()) != null) {
writer.write(line);
writer.newLine();
}
reader.close();
}
writer.close();
Here is what you might be looking for.
I have read two csv files and written into one.
Hope this is use full...
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
public class CombineTwoFile
{
public static void main(String[] args) throws IOException
{
ArrayList<String> list = new ArrayList<String>();
try
{
BufferedReader br = new BufferedReader(new FileReader( "d:\\1\\1.csv"));
BufferedReader r = new BufferedReader(new FileReader( "d:\\1\\2.csv"));
String s1 =null;
String s2 = null;
while ((s1 = br.readLine()) != null)
{
list.add(s1);
}
while((s2 = r.readLine()) != null)
{
list.add(s2);
}
}
catch (IOException e)
{
e.printStackTrace();
}
BufferedWriter writer=null;
writer = new BufferedWriter(new FileWriter("d:\\1\\good.csv"));
String listWord;
for (int i = 0; i< list.size(); i++)
{
listWord = list.get(i);
writer.write(listWord);
writer.write("\n");
}
System.out.println("DONE Enjoy!!");
writer.close();
}
}
Or if you looking for a function which returns String combining two csv
public static String combineCSV() {
ArrayList<String> list = new ArrayList<String>();
try {
BufferedReader br = new BufferedReader(new FileReader(
"d:\\1\\1.csv"));
BufferedReader r = new BufferedReader(
new FileReader("d:\\1\\2.csv"));
String s1 = null;
String s2 = null;
while ((s1 = br.readLine()) != null) {
list.add(s1);
}
while ((s2 = r.readLine()) != null) {
list.add(s2);
}
} catch (IOException e) {
e.printStackTrace();
}
String listWord;
StringBuffer objBuffer = new StringBuffer();
for (int i = 0; i < list.size(); i++) {
listWord = list.get(i);
objBuffer.append(listWord);
objBuffer.append("\n");
}
System.out.println("DONE Enjoy!!");
System.out.println(objBuffer);
return objBuffer.toString();
}
Thank you!!!!
Enjoy Coding...
Another alternative is to use Open CSV library
The code below only brings up the first line of code and stops. I would like to return each line of code until there are no more.
private String GetPhoneAddress() {
File directory = Environment.getExternalStorageDirectory();
File myFile = new File(directory, "mythoughtlog.txt");
//File file = new File(Environment.getExternalStorageDirectory() + "mythoughtlog.txt");
if (!myFile.exists()){
String line = "Need to add smth";
return line;
}
String line = null;
//Read text from file
//StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(myFile));
line = br.readLine();
}
catch (IOException e) {
//You'll need to add proper error handling here
}
return line;
}
You could loop over the results of readLine() and accumulate them until you get a null, indicating the end of the file (BTW, note that your snippet neglected to close the reader. A try-with-resource structure could handle that):
try (BufferedReader br = new BufferedReader(new FileReader(myFile))) {
String line = br.readLine();
if (line == null) {
return null;
}
StringBuilder retVal = new StringBuilder(line);
line = br.readLine();
while (line != null) {
retVal.append(System.lineSeparator()).append(line);
line = br.readLine();
}
return retVal.toString();
}
if you're using Java 8, you can save a lot of this boiler-plated code with the newly introduced lines() method:
try (BufferedReader br = new BufferedReader(new FileReader(myFile))) {
return br.lines().collect(Collectors.joining(System.lineSeparator()));
}
A considerably less verbose solution:
try (BufferedReader br = new BufferedReader(new FileReader(myFile))) {
StringBuilder retVal = new StringBuilder();
while ((line = br.readLine()) != null) {
retVal.append(line).append(System.lineSeparator());
}
return retVal.toString();
}
This question already has answers here:
Bufferedwriter works, but file empty?
(4 answers)
Closed 6 years ago.
I was trying to append a text in text file. I am using some new classes added in Java 7. But with my code nothing is added in text file. I have tried some debugging but not getting why it is not writing a text in file.
Here is a code:
public void input(String path, PrintWriter out) throws FileNotFoundException, IOException
{
String finalstring;
FileInputStream in = new FileInputStream(path);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
Path FILE_PATH = Paths.get("C:/10", "tweets_6.txt");
BufferedWriter writer = Files.newBufferedWriter(FILE_PATH, StandardCharsets.UTF_8, StandardOpenOption.APPEND);
String line;
while((line = br.readLine()) != null)
{
finalstring = line;
URLEntity u;
finalstring = finalstring.replaceAll("https?://\\S+\\s?", "");
finalstring=finalstring.replace("#engineeringproblems", " ");
finalstring=finalstring.replace("#", " ");
// Stemming Algorithm
StringTokenizer st = new StringTokenizer(finalstring);
String finalstring1;
finalstring = "";
while (st.hasMoreTokens())
{
KrovetzStemmer ks = new KrovetzStemmer();
finalstring1 = ks.stem(st.nextToken());
// repeated characters remover
finalstring1 = finalstring1.replaceAll("(.)\\2{2,}", "$2");
FileInputStream in1 = new FileInputStream("C:\\10\\NonWords.txt");
BufferedReader br1 = new BufferedReader(new InputStreamReader(in1));
FileInputStream in2 = new FileInputStream("C:\\10\\StopWords.txt");
BufferedReader br2 = new BufferedReader(new InputStreamReader(in2));
String line1;
String line2;
while((line1 = br1.readLine()) != null)
{
if(finalstring1.equals(line1))
{
finalstring += finalstring1 + " ";
}
}
while((line2 = br2.readLine()) != null)
{
if(finalstring1.equals(line2))
{
finalstring += finalstring1 + " ";
}
}
}
writer.write(finalstring);
writer.newLine();
}
}
Please suggest a change in my code. Something I am missing here.
You're using a writer, and they need to be closed. On top of that, you're using a BufferedWriter so you won't necessarily see any output before it's closed.