I have a code which produces 3 values x,y,z.
x,y,z will be updating every moment.
I need to write these values to csv file in java.
Help me
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String tempX = String.valueOf(lastX);
String tempY = String.valueOf(lastY);
String tempZ = String.valueOf(lastZ);
// System.out.println("x value: " + temp);
CSVWriter csv = null;
try {
csv = new CSVWriter(new FileWriter("/sdcard/myfile.csv"), ',');
//List<String> lists = new ArrayList<String>();
String[] values = new String[]{tempX,tempY,tempZ,"1"};
csv.writeNext(values);
csv.close();
Toast.makeText(getApplicationContext(), "Able to write CSV", Toast.LENGTH_LONG).show();
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "Unable to write CSV", Toast.LENGTH_LONG).show();
}
}
Instead of looping through entries of String[] array and writing it to CSV you can pass the entire array as follow:
/*
* bellow will insert values array values.length times,
*/
for(int i=0;i<values.length;i++){
csv.writeNext(values);
}
Replacing above with below, writes all the entries of array to CSV
csv.writeNext(values);
I have come up with the following solution using the OpenCSV. For testing purpose, I have added a loop to insert values to the CSV to give you an idea how you can update the CSV.
import java.io.FileWriter;
import java.io.IOException;
import com.opencsv.CSVWriter;
public class OpenCSVTest {
public static void main(String[] args) {
CSVProcessor process = new CSVProcessor();
String[] entries = new String[]{"1","2","3","x"};
//assume each loop is when you get updated entries
for(int i = 0; i < 5; i++) {
//store to the file
process.storeUpdatedValues(entries);
//change the vaues to simulate update in x,y,z
entries[0] = entries[0] + 5;
entries[1] = entries[1] + 10;
entries[2] = entries[2] + 3;
entries[3] = entries[3] + "i:" + i;
}
}
}
class CSVProcessor {
public void storeUpdatedValues(String[] entries) {
CSVWriter writer;
try {
/*
* First arg to CSVWriter is FileWriter that references your file in the disk
* Second arg to the CSVWriter is the delimiter, can be comma, tab, etc.
* First arg to FileWriter is location of your file to write to
* Second arg to FileWriter is a flag stating that if file found then append to it
*/
writer = new CSVWriter(new FileWriter("C:\\test_java\\yourfile.csv", true), ',');
// feed in your array - you don't need to loop through the items of array
writer.writeNext(entries);
// close the writer.
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
You get the following output when you run the program once (5 rows because loop is run five times):
1 2 3 x
15 210 33 xi:0
155 21010 333 xi:0i:1
1555 2101010 3333 xi:0i:1i:2
15555 210101010 33333 xi:0i:1i:2i:3
Steps to use the CSVProcessor class:
Instantiate it and create an object
Whenever the values of x,y,z are updated then pass them to instance of CSVProcessor
Repeat line 2 whenever x,y,z is updated. Your updates will get appended to the CSV.
Use FileWrite to write x,y,z into a csv file.
Please read this code sample. It is self-explanatory.
import java.io.FileWriter;
import java.io.IOException;
private static final String COMMA_DELIMITER = ",";
private static final String NEW_LINE_SEPARATOR = "\n";
private static final String FILE_HEADER = "x,y,z";
FileWriter fileWriter = null;
try {
fileWriter = new FileWriter(fileName);
fileWriter.append(FILE_HEADER.toString());
fileWriter.append(NEW_LINE_SEPARATOR);
// Write x, y, z
fileWriter.append(x);
fileWriter.append(y);
fileWriter.append(z);
System.out.println("CSV file was created successfully !!!");
} catch (Exception e) {
System.out.println("Error in CsvFileWriter !!!");
e.printStackTrace();
} finally {
try {
fileWriter.flush();
fileWriter.close();
} catch (IOException e) {
System.out.println("Error while flushing/closing fileWriter !!!");
e.printStackTrace();
}
}
http://examples.javacodegeeks.com/core-java/writeread-csv-files-in-java-example/
Related
i need to replace the first line in the text file with the longest and vice versa. Please tell me what i need to fix and add. At this stage the program looks for the longest line properly. I'm new to Java, I'm sure there is not much to fix, but I do not know what exactly is needed. Also, if possible, help implement the output of the result in a new file.
The code still looks like this:
package pkg;
import java.io.*;
import java.nio.file.Files;
import java.util.*;
public class Main {
static int previousLongLine = 0;
public void printLongLine(HashMap longLineMap) {
Set keyofSet = longLineMap.keySet();
Iterator itr = keyofSet.iterator();
while (itr.hasNext()) {
Integer keys = (Integer) itr.next();
String value = (String) longLineMap.get(keys);
System.out.println("Line Number of Longest line: " + keys
+ "\nLongest line: " + value);
}
}
public static void main(String []args){
// TODO Auto-generated method stub
String fileName = "G:\\colege\\bursa\\Colege\\Programing\\pkg\\File1.txt";
// This will reference one line at a time
String line = null;
int key = 0;
int lineSize = 0, lineNumber = 0;
Main ln = new Main();
HashMap longLineMap = new HashMap();
try {
// FileReader reads text files in the default encoding.
FileReader fileReader = new FileReader(fileName);
// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader = new BufferedReader(fileReader);
while ((line = bufferedReader.readLine()) != null) {
lineNumber++;
lineSize = line.length();
if (lineSize > previousLongLine) {
previousLongLine = lineSize;
longLineMap.clear();
longLineMap.put(lineNumber, line);
}
if(lineNumber == 1){
String old = line;
String newl = old.replaceFirst(old, String.valueOf(previousLongLine));
}
}
//close files.
bufferedReader.close();
} catch (FileNotFoundException ex) {
System.out.println("Unable to open file '" + fileName + "'");
} catch (IOException ex) {
System.out.println("Error reading file '" + fileName + "'");
}
ln.printLongLine(longLineMap);
}
}
You can achieve this with a simple stream operation.
Info on stream: https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html
I've used try-with-resource, which auto-closes the resource after processing has ceased.
Info on try-with-resource: https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
Read file into an ArrayList
Create another List to hold the sorted elements.
Open a stream on the ArrayList which holds the input data.
Sort the lines into size order. Use Comparator.reverseOrder() for largest to smallest
Using a downstream collector store the output as a new list.
Write sorted list to file.
Reading file:
String inputFile = "files/longestLine.txt";
List<String> lines = new ArrayList<>();
try(BufferedReader bufferedReader = new BufferedReader(new FileReader(inputFile))) {
String line = bufferedReader.readLine();
while(line != null){
lines.add(line);
line = bufferedReader.readLine();
}
} catch (IOException e) {
e.printStackTrace();
}
Use a stream to sort the lines into size order.
List<String> sortedLines = lines.stream()
.sorted(Comparator.reverseOrder())
.collect(Collectors.toList());
Write to file:
String outputFile = "outputFile.txt";
try(BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(outputFile))) {
for (String line: sortedLines) {
bufferedWriter.write(line);
bufferedWriter.newLine();
}
} catch (IOException e) {
e.printStackTrace();
}
I'm trying to convert .dat file to csv file but I have a problem with it. Below is my code:
public class Main {
public static void main(String[] args) {
DatToCsv dataToCsv = new DatToCsvImpl(); //creating object of DataToCsvImpl class
try {
// Three parameter should be giving to convertDatToCsv function namely input file location and output file
// location and fixed column size respectively
dataToCsv.convertDatToCsv("testing.dat", "testing.csv", 5);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Code 2:
public interface DatToCsv {
public void convertDatToCsv(String datFileLocation,String outputFile, int column)throws IOException;
}
Code 3:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class DatToCsvImpl implements DatToCsv {
#Override
public void convertDatToCsv(String datFileLocation, String outputFile, int column) throws IOException {
// creating instance of file writer, buffer reader and writer
String st;
FileWriter writer;
BufferedWriter bw;
BufferedReader br;
String csvData = "";
int count = 0;
try {
File file = new File(datFileLocation); // .dat file location
writer = new FileWriter(outputFile); // .csv file location
bw = new BufferedWriter(writer); // giving writer to buffer writer constructor to initilize
br = new BufferedReader(new FileReader(file)); // giving input file (.dat) file to buffer reader
StringBuilder sb = new StringBuilder();
/*
* Using while loop (as long as) upto end of file getting data by line by line
*/
while ((st = br.readLine()) != null) {
/*
* replacing multiple space into single space and comma separated of single
* space
*/
st = st.trim().replaceAll(" +", ",");
// if first line of file consider to be heading
if (count == 0) {
csvData = st;
} else {
csvData = csvData + "," + st;
}
count++;
}
// converting all comma seperated value to string array
String csvArray[] = csvData.split(",");
int runningCount = 1;
for (String str : csvArray) {
if (runningCount == column) { // compare fixed column size to running count every fixed column size new
// line added \n
sb.append(str + "\n");
runningCount = 1;
} else {
sb.append(str + ","); // otherwise comma added at the end of every key
runningCount++;
}
}
bw.write(sb.toString());
/*
* flush is because if data 1024bytes not it not store to csv file so we need to
* explicitly mention push data to csv
*/
bw.flush();
writer.close();
br.close();
bw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
For whatever reason it doesnt work and it doesnt accept my input and the output is nowhere to be found. I have tried googling for help to find the input and output but I still couldnt do it. Any help is appreciated thanks
I am trying to read a .txt file that is not a fixed length and convert it to a certain fixed length. I tried using an array in the while loop for each line that is read to be split() but it kept giving me weird formats, so I took it out! I wanted the institution to be formatted for 40 char lengths, v_25 - sub variables to be a fixed length of 3, and the enrollment variable to be set at 4! Please help!
import java.io.*;
public class FileData {
public static void main (String[] args) {
File file = new File("test.txt");
StringBuffer contents = new StringBuffer();
BufferedReader reader = null;
// int counter = 0;
String institution = null;
String V_25 = null;
String V_75 = null;
String M_25 = null;
String M_75 = null;
String Submit = null;
String Enrollment = null;
try {
reader = new BufferedReader(new FileReader("/Users/GANGSTATOP/Documents/workspace/DBTruncate/src/input.txt"));
String text = null;
// repeat until all lines is read
while ((text = reader.readLine()) != null) {
contents.append(text.replaceAll(",", " ")).append("\nblank\n");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
// show file contents here
System.out.println(contents.toString());
}
}
Originally reading the file:
Adelphi University,500,600,510,620,715,7610
Alabama State University,380,470,380,480,272,5519
How I am trying to make it look like:
(institution) (v_25) (v_75) (m_25) (m_75) (sub) (enroll)
Adelphi University 500 600 510 620 715 7610
blank
Alabama State University 380 470 380 480 272 5519
blank
Here is my suggestion:
BufferedReader reader = null;
List<String> list = new ArrayList<>();
try {
reader = new BufferedReader(new FileReader("input.txt"));
String temp;
while ((temp= reader.readLine()) != null) {
list.add(temp);
}
}
catch (FileNotFoundException e) { e.printStackTrace(); }
catch (IOException e) { e.printStackTrace(); }
finally {
try { if (reader != null) { reader.close(); } }
catch (IOException e) { e.printStackTrace(); }
}
System.out.println(String.format("%12s%12s%12s%12s%12s%12s\n\n",
"v_25", "v_72", "m_25", "m_75", "Sub", "Enroll"));
for(int i= 0;i < list.size();i++){
String temp2[] = list.split(",");
if(temp2.length == 6){
System.out.println(String.format("%12s%12s%12s%12s%12s%12s\n\n", temp2[0], temp2[1],temp2[2],temp2[3],temp2[4],temp2[5]);
}
else{
System.out.println("Error");
}
}
That would be my first draft for an answer.
In my opinion you should use an Array and by array I mean a java.util.ArrayList or java.util.List interface, for example:
List<String> list = new ArrayList<>();
A List can easily be added to and grow (among many other things) without the need to initialize it to a specific size as you would with let's say a String[] Array. Since we don't know how many lines of data may be contained within the data file (input.txt) use of the List Interface is a really good way to go, for example:
Required Imports:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
Code to carry out the task:
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader("/Users/GANGSTATOP/Documents/workspace/DBTruncate/src/input.txt"));
String text;
List<String> list = new ArrayList<>(); // To hold file data
int longestLength = 0; // Longest University name length
while ((text = reader.readLine()) != null) {
// Add text line to our list array
list.add(text);
// Get the longest length of University names
// for display purposes later on.
if (!text.isEmpty()) {
if (longestLength < text.indexOf(",")) { longestLength = text.indexOf(","); }
}
}
// Sort the List
Collections.sort(list);
// Create & display the Header Line...
String sv = "Institution";
while (sv.length() < longestLength) { sv+= " "; }
sv+= " v_25 v_75 m_25 m_75 Sub Enroll";
System.out.println(sv);
// Create & display the Header Underline...
String ul = "=";
while (ul.length() < (sv.length())) { ul+= "="; }
System.out.println(ul + "\n");
// Iterate through & display the Data...
for (int i = 0; i < list.size(); i++) {
// Pull out the University name from List
// element and place into variable un
String un = list.get(i).substring(0, list.get(i).indexOf(","));
// Right Pad un with spaces to match longest
// University name. This is so everthing will
// tab across console window properly.
while (un.length() < longestLength) { un+= " "; }
// Pull out the university data and convert the
// comma delimiters to tabs then place a newline
// tag at end of line so as to display a blank one.
String data = list.get(i).substring(list.get(i).indexOf(",")+1).replace(",", "\t") + "\n";
//Display the acquired data...
System.out.println(un + "\t" + data);
}
}
catch (FileNotFoundException e) { e.printStackTrace(); }
catch (IOException e) { e.printStackTrace(); }
finally {
try { if (reader != null) { reader.close(); } }
catch (IOException e) { e.printStackTrace(); }
}
Once all the file data is contained within the List, hardware access is no longer required and all the data within the List can be easily retrieved, sorted, and manipulated as you see fit unless of course if the data file is quite large and you want to work in Data Chunks.
Here's my solution to your problem. Maybe this is what you've been searching for.
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
public class FileData {
public static void main (String[] args) {
FileData fileData = new FileData();
String file = "C:\\Development\\sandbox\\test.txt";
StringBuffer contents = new StringBuffer();
String headline = "(Institution)\t\t\t\t\t(V_25)\t(V_75)\t(M_25)\t(M_75)\t(sub)\t(enrol)\n";
// insert the headline
contents.append(headline);
// read the file and convert it. At this point you've got a list of maps,
// each map containing the values of 1 line addressed by the belonging key
ArrayList<HashMap<String, String>> fileContent = fileData.readData(file);
// now you're going to assemble your output-table
for(HashMap<String, String> lineContent : fileContent){
// Add the institution, but adjust the string size before
contents.append(fileData.stringSizer(lineContent.get("Institution")));
// Add a tab and the next value
contents.append("\t");
contents.append(lineContent.get("V_25"));
// Add a tab and the next value
contents.append("\t");
contents.append(lineContent.get("V_75"));
// Add a tab and the next value
contents.append("\t");
contents.append(lineContent.get("M_25"));
// Add a tab and the next value
contents.append("\t");
contents.append(lineContent.get("M_75"));
// Add a tab and the next value
contents.append("\t");
contents.append(lineContent.get("Submit"));
// Add a tab and the next value
contents.append("\t");
contents.append(lineContent.get("Enrollment"));
// add a new line the word "blank" and another new line
contents.append("\nblank\n");
}
// That's it. Here's your well formed output string.
System.out.println(contents.toString());
}
private ArrayList<HashMap<String, String>> readData(String fileName){
String inputLine = new String();
String[] lineElements;
ArrayList<HashMap<String, String>> fileContent = new ArrayList<>();
HashMap<String, String> lineContent;
// try with resources
try(BufferedReader LineIn = new BufferedReader(new FileReader(fileName))) {
while ((inputLine = LineIn.readLine()) != null){
// every new line gets its own map
lineContent = new HashMap<>();
// split the current line up by comma
lineElements = inputLine.split(",");
// put each value indexed by its key into the map
lineContent.put("Institution", lineElements[0]);
lineContent.put("V_25", lineElements[1]);
lineContent.put("V_75", lineElements[2]);
lineContent.put("M_25", lineElements[3]);
lineContent.put("M_75", lineElements[4]);
lineContent.put("Submit", lineElements[5]);
lineContent.put("Enrollment", lineElements[6]);
// add the map to your list
fileContent.add(lineContent);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// everything went well. Return the list.
return fileContent;
}
private String stringSizer(String value){
// if value is longer than 40 letters return the trimmed version immediately
if (value.length() > 40) {
return value.substring(0, 40);
}
// if values length is lower than 40 letters, fill in the blanks with spaces
if (value.length() < 40) {
return String.format("%-40s", value);
}
// value is exactly 40 letters long
return value;
}
}
I have a I/O java file, a SDive file which contains main, a .txt Directory file that has random words in it and a Sorted .txt to return the random words in order ascending to descending. It print all the words in the Sorted but it is not sorted.
//Sort.java
// required for input
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
// required for output
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
class Sort{
private String[] tArr = new String[100];
public void swap(int j) {
String temp = tArr[j-1];
tArr[j-1] = tArr[j];
tArr[j] = temp;
}
///Bubble sort
public void sort() {
int n = tArr.length;
for(int i = 0; i < n; i++) {
for(int j = 1; j < n-i; j++) {
if(tArr[j-1].compareTo(tArr[j]) > 0) {
swap(j);
}
}
}
}
public void read() {
System.out.println("in read()");
String pwd = System.getProperty("user.dir");
String fileName = pwd + "/directory.txt";
System.out.println("Looking for: " + fileName);
String fileLine = "";
try {
File f = new File(fileName);
if(f.exists()) {
System.out.println("Directory profile found, loading data...");
}
else {
System.out.println("Directory profile not found, loading default...");
return; // done, return back to the caller
}
// Read file
FileReader data = new FileReader(fileName);
// Wrap FileReader with BufferedReader
BufferedReader br = new BufferedReader(data);
//String tmp;
int i=0;
while ((fileLine = br.readLine()) != null) {
tArr[i++] = fileLine;
}
// ok, time to load an existing profile
// close the file
br.close();
} catch (FileNotFoundException fnf) {
System.out.println("File not found: " + fileName);
} catch (IOException ioe) {
System.out.println("Error reading file: " + fileName);
} catch (Exception exc) {
System.out.println("Something went wrong: " + fileName);
}
}
public void write() {
System.out.println("in write()");
String pwd = System.getProperty("user.dir");
String fileName = pwd + "/Sorted.txt";
try {
System.out.println("Writing out to: " + fileName);
File file = new File(fileName);
// creates the file
file.createNewFile();
// create FileWriter object
FileWriter writer = new FileWriter(file);
// output to file
// ADD pIdx, pArr, mood, and anything else here...
for(int i = 0; i < tArr.length; i++) {
writer.write(tArr[i] + "\n");
}
writer.flush();
writer.close();
} catch (IOException ex) {
System.out.println("Error writing to file: " + fileName);
}
}
}
And my main file is SDrive:
class SDriver{
public static void main(String args []){
Sort io = new Sort();
io.read();
io.write();
}
}
You should add the io.sort() method after io.read(); line and just before io.write(); line.
I see you use bubble sort, if you really want to implement your own sorting method take a look at quick sort and merge sort which are much much faster than bubble sort on larger arrays but also harder to implement. Insertion and Selection sort are not as fast as merge or quick but still faster than bubble and still as easy to self implement. Or use Arrays.sort(tArr); if you want to do it quick.
I am trying to write a simple method to save my document to a file (overwriting any previous contents of the file.) Unfortunately, my implementation does not seem to work. I am calling it on my document, which is, for all intents and purposes, an array of String. What I'd like to do is to write the contents of my array, with a separate line for each value in the array, the value in position [0] on the first line, and the value for [1] on the second. How would I go about this ?
This is my implementation so far :
public void save()
{
try
{
PrintWriter outputFile =
new PrintWriter(new BufferedWriter(new FileWriter(docName)));
int lineNo = 1;
while (lineNo != lineNo) // CHANGE THIS!!!
{ outputFile.println(" ~ ");
lineNo++;
}
outputFile.flush();
}
catch (Exception e)
{
System.out.println("Document: Touble writing to "+docName);
System.exit(1);
}
}
If a is an array of strings,
for (String s : a)
outputFile.println(s);
will print the array line-by-line to outputFile.
Iterator over the array, and write the current element.
String document[] = {"String1","String2","String3"};
PrintWriter outputFile =
new PrintWriter(new BufferedWriter(new FileWriter(docName)));
int lineNo = 1;
for(int i = 0; i < document.length; i++)
{ outputFile.println(document[i]);
lineNo++;
}
// myDoc is the "array of string"
foreach (String line : myDoc) {
outputFile.println(line);
}
I might write it more like this:
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
/**
* FileDemo
* #author Michael
* #since 2/26/11
*/
public class FileDemo
{
public static void main(String[] args)
{
try
{
FileDemo fd = new FileDemo();
fd.save("out/test.txt", args);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
public void save(String filePath, String [] lines) throws FileNotFoundException
{
PrintStream ps = null;
try
{
ps = new PrintStream(new FileOutputStream(filePath));
int lineNum = 1;
for (String line : lines)
{
ps.printf("%5d %s\n", lineNum++, line);
}
}
finally
{
close(ps);
}
}
public static void close(PrintStream ps)
{
if (ps != null)
{
ps.flush();
ps.close();
}
}
}
I didn't see any actual content in your code, so I added some. I didn't how a file with line numbers was very interesting. You'd be able to modify this to make it differently if you wish.