I'm trying to emulate the Save As functionality in Java.
I want to choose a filename for it as the code I did before only saved it to
myData.dat
this is used in a menu in my Main.Class which will look up to
else if (option.compareTo("8") == 0){
manualLib.save();}
public void save(){
String content = "";
for (int i = 0; i < library.size(); i++){
for (int bar = 0; bar < library.get(i).size(); bar++){
content += library.get(i).get(bar).getSerial() + "\n";
content += library.get(i).get(bar).getTitle() + "\n";
content += library.get(i).get(bar).getAuthor() + "\n";
content += library.get(i).get(bar).onLoan() + "\n";
content += library.get(i).get(bar).getBorrower() + "\n";
}
}
Writer output;
try {
output = new BufferedWriter(new FileWriter("myData.dat"));
try {
output.write(content);
}
finally {
output.close();
System.out.println("Successfully saved to myData.dat file.");
}
} catch (IOException e) {
e.printStackTrace();
}
}
What is a good way of achieving this?
You could use a JFileChooser. This will give you an "easy" UI to let the user choose a file (or a filename). Then you will substitute your myData.dat with the value returned by chooser.getSelectedFile().getName().
I have not compiled this but your code should in the end look something like:
public void save(){
String content = "";
for (int i = 0; i < library.size(); i++){
for (int bar = 0; bar < library.get(i).size(); bar++){
content += library.get(i).get(bar).getSerial() + "\n";
content += library.get(i).get(bar).getTitle() + "\n";
content += library.get(i).get(bar).getAuthor() + "\n";
content += library.get(i).get(bar).onLoan() + "\n";
content += library.get(i).get(bar).getBorrower() + "\n";
}
}
Writer output;
JFileChooser chooser = new JFileChooser();
DatFilter filter = new DatFilter();
filter.addExtension("dat");
filter.setDescription(".dat files");
chooser.setFileFilter(filter);
int returnVal = chooser.showOpenDialog(null);
String fileName = new String();
if(returnVal == JFileChooser.APPROVE_OPTION) {
fileName=chooser.getSelectedFile().getName();
}
try {
output = new BufferedWriter(new FileWriter(fileName));
try {
output.write(content);
}
finally {
output.close();
System.out.println("Successfully saved to "+fileName+" file.");
}
} catch (IOException e) {
e.printStackTrace();
}
}
Then make also class
public class DatFilter extends FileFilter {
//should accept only dirs and .dat files
public boolean accept(File f) {
if (f.isDirectory()) {
return true;
}
String extension = null;
String s = f.getName();
int i = s.lastIndexOf('.');
if (i > 0 && i < s.length() - 1) {
extension = s.substring(i+1).toLowerCase();
}
if (extension != null) {
if (extension.equals("dat"){
return true;
} else {
return false;
}
}
return false;
}
//The description of this filter
public String getDescription() {
return ".dat Files";
}
}
Use a JFileChooser or whatever UI of your choice to get a full path to the target file to create.
add a parameter to your save method to get this path, and use it instead of myData.dat
store the file path in a field of Main.class
add a save without parameter, that calls the save parameter using the path stored in Main.class.
Related
I am dividing my file into chunks but only problem i am facing is,
i have .srt file, but while doing chunks, it's cutting the characters i.e in first .srt file it's like 00:26:20,230 --> . in next file it continuing the next time stamp 00:27:40,343.
I need to check the timestamp to be complete and then next full subtitle sentence too. i.e if it's cutting the subtitle timesstamp or dialogue in in file, that tect to be append to next file. Please suggest me how can i achieve.
I am trying like below,
String FilePath = "/Users/meh/Desktop/escapeplan.srt";
FileInputStream fin = new FileInputStream(FilePath);
System.out.println("size: " +fin.getChannel().size());
long abc = 0l;
abc = (fin.getChannel().size())/3;
System.out.println("6: " +abc);
System.out.println("abc: " +abc);
//FilePath = args[1];
File filename = new File(FilePath);
long splitFileSize = 0,bytefileSize=0;
if (filename.exists()) {
try {
//bytefileSize = Long.parseLong(args[2]);
splitFileSize = abc;
Splitme spObj = new Splitme();
spObj.split(FilePath, (long) splitFileSize);
spObj = null;
} catch (Exception e) {
e.printStackTrace();
}
} else {
System.out.println("File Not Found....");
}
public void split(String FilePath, long splitlen) {
long leninfile = 0, leng = 0;
int count = 1, data;
try {
File filename = new File(FilePath);
InputStream infile = new BufferedInputStream(new FileInputStream(filename));
data = infile.read();
System.out.println("data");
System.out.println(data);
while (data != -1) {
filename = new File("/Users/meh/Documents/srt" + count + ".srt");
//RandomAccessFile outfile = new RandomAccessFile(filename, "rw");
OutputStream outfile = new BufferedOutputStream(new FileOutputStream(filename));
while (data != -1 && leng < splitlen) {
outfile.write(data);
leng++;
data = infile.read();
}
leninfile += leng;
leng = 0;
outfile.close();
changeTimeStamp(filename, count);
count++;
}
} catch (Exception e) {
e.printStackTrace();
}
}
i am trying to check the time stamp is in correct format or not. Then i need to check next line to be a dialogue and then the next line to be empty line. then it can stop chunk or else it should append the text from the previous chunk to next chunk file in the beginning of line . so that it may get in correct format.
I tried checking the format like,
while ((strLine = br.readLine()) != null) {
String[] atoms = strLine.split(" --> ");
if (atoms.length == 1) {
out.write(strLine + "\n");
} else {
String startTS = atoms[0];
String endTS = atoms[1];
System.out.print("sri atmos start" + startTS);
System.out.print("sri atmos end" + endTS);
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss,SSS");
sdf.setLenient(false);
try
{
sdf.parse(startTS);
sdf.parse(endTS);
System.out.println("Valid time");
System.out.println("File path" + srcFileNm);
}
catch(Exception e) {
System.out.println("Invalid time");
System.out.println("Exception start" + startTS);
System.out.println("Exception end" + endTS);
}
}
some screens of my output chunks,
Help me how can i make this possible.
I think you should change approach, and fully use basic I/O methods. I tried to encapsulate logic in a small class, that produces a triple with id, msecs and a list of subtitles (if I'm not wrong, you can have more than a line). Then I leaved the remainder externally. Chunker is a class that reads a triple (class Three) from file, so that you can manage it and write it somewhere.
This is just a "quick&dirty" idea that you can refine, but it should work.
package org.norsam.stackoverflow;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class Chunker
{
BufferedReader r;
int chunk = 0;
File dir;
public Chunker(File dir, String filename) throws IOException
{
File f = new File(dir, filename);
this.dir = dir;
this.r = new BufferedReader(new FileReader(f));
}
public Three readThree() throws IOException
{
Integer id = Integer.parseInt(r.readLine());
String msecs = r.readLine();
String s = null;
List<String> srt = new ArrayList<>();
while (!(s = r.readLine().trim()).isEmpty()) {
srt.add(s);
}
return new Three(id, msecs, srt);
}
class Three
{
Integer id;
String msecs;
List<String> srts;
Three(Integer id, String msecs, List<String> srts)
{
this.id = id;
this.msecs = msecs;
this.srts = srts;
}
Three doSomething() {
// here you can do something with your data,
// e.g. split msecs on "-->" and check times
return this;
}
void write(BufferedWriter r) throws IOException
{
r.write(id);
r.newLine();
r.write(msecs);
r.newLine();
for (String s : srts) {
r.write(s);
r.newLine();
}
r.newLine();
}
}
public static void main(String[] args) throws IOException
{
String baseDir = "/dir/where/resides/srt";
String filename = "filename.srt";
int elemPerChunk = 50;
int fileNum = 0;
File dir = new File(baseDir);
Chunker chunker = new Chunker(dir, filename);
boolean completed = false;
while (!completed) {
int srtCount = 0;
File f = new File(baseDir, "ch." + (fileNum++) + "." + filename);
BufferedWriter w = new BufferedWriter(new FileWriter(f));
try {
while (srtCount++ < elemPerChunk) {
chunker.readThree().doSomething().write(w);
}
} catch (NullPointerException e) {
completed = true;
}
w.close();
}
}
}
how to get a maximum value of two peaks of an array and take them away using for loops? any ideas?
was thinking to use 2 for loops to find the values in the array. i am using an acceloremeter and displaying the result within a graph but now i need to find the 2 peaks and take them away to determine the outcome and display it.
SM.unregisterListener(this);
File path = getApplicationContext().getExternalFilesDir(null);
File file = new File(path, "my_file-name.txt");
// String filename = "my_file";
FileOutputStream outputStream;
try {
outputStream = new FileOutputStream(file); //openFileOutput(file, Context.MODE_APPEND);
for (double d : array) {
String s = Double.toString(d) + ",";
outputStream.write(s.getBytes());
}
String newline = "/n";
outputStream.write(newline.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
this code values are stored within a file so i can then display it within a graph
Here is how you can find two peaks in one loop:
File file = new File(path, "my_file-name.txt");
// String filename = "my_file";
FileOutputStream outputStream;
try {
outputStream = new FileOutputStream(file); //openFileOutput(file, Context.MODE_APPEND);
double peak1, peak2;
if(array.length >= 2) {
peak1 = array[0];
peak2 = array[1];
} else { // not enough elements
return;
}
for (double d : array) {
// peak2 is greater, leave it;
// save new value to peak1 ?
if(peak1 < peak2 && d > peak1) {
peak1 = d;
} else if(d > peak2) { // peak1 is greater or d is less
peak2 = d;
}
String s = Double.toString(d) + ",";
outputStream.write(s.getBytes());
}
String newline = "/n";
outputStream.write(newline.getBytes());
outputStream.close();
System.out.println("Peaks: " + peak1 + " ; " + peak2);
} catch (Exception e) {
System.out.println("Error: " + e);
//e.printStackTrace();
}
See code sample here.
private void stopSensor() {
SM.unregisterListener(this);
File path = getApplicationContext().getExternalFilesDir(null);
File file = new File(path, "my_file-name.txt");
// String filename = "my_file";
FileOutputStream outputStream;
try {
outputStream = new FileOutputStream(file); //openFileOutput(file, Context.MODE_APPEND);
for (double d : array) {
String s = Double.toString(d) + ",";
outputStream.write(s.getBytes());
}
String newline = "/n";
outputStream.write(newline.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
try {
double peak1, peak2;
int peaklocation1, peaklocation2;
if (array.length >= 2) {
peak1 = array[0];
peak2 = array[1];
peaklocation1 = 0;
peaklocation2 = 1;
} else { // not enough elements
return;
}
for (int i = 0; i < array.length; i++) {
double d = array[i];
// peak2 is greater, leave it;
// save new value to peak1 ?
if (peak1 < peak2 && d > peak1) {
peak1 = d;
peaklocation1 = i;
} else if (d > peak2) { // peak1 is greater or d is less
peak2 = d;
peaklocation2 = i;
}
}
int size = peaklocation1;
size = peaklocation1 - peaklocation2 ;
resultText.setText("Result:" + peaklocation1 );
resultText2.setText("Result:" + peaklocation2);
} catch (Exception e) {
// System.out.println("Error: " + e);
//e.printStackTrace();
}
i have a really suspicious case here, envolving a simple method which is supposed to write into a .txt file.
public void extractCoNLL(int n, String outputFile) throws IOException {
String msg;
PrintWriter pr = new PrintWriter(outputFile);
FileInputStream fConlliN = new FileInputStream(this.txt_CoNLL_in);
BufferedReader readBufferData = new BufferedReader(new InputStreamReader(fConlliN));
try {
while ((msg = readBufferData.readLine()) != null) {
String aMsg[] = msg.split("\\s+");
if (!msg.startsWith("#")) {
//pr.println(msg);
if (aMsg.length >= n) {
pr.print(aMsg[n] + "_"); // DOES NOT WORK
pr.println(aMsg[n] + "_"); // WORKS ?????
System.out.println(aMsg[4] + aMsg.length);
} else {
pr.println();
}
}
}
this.txt_CoNLL = out_Extracted_txt_CoNLL;
} catch (Exception e) {
System.err.println("Error Exception: " + e.getMessage());
}
}
Also, why is it not possible for me to add a simple " " -space but i have to be forced to use "_" to seperate the words.
Very grateful for your Help.
Thank you in advance!
I have converted the db file into csv file and worked perfectly in android. But I manually deleted the csv file from storage location and try to run the same code. but I am unable to write the file into the same location. No exception noticed.
The code used is as follows:
public void exportTopic() {
int rowCount, colCount;
int i, j;
Cursor c=null;
SQLHelper helperr=null;
try {
helperr=new SQLHelper(getActivity());
c = helperr.getAllTopics();
Log.d("exportPath", sdCardDir.getPath());
String filename = "MyBackUp.csv";
File CsvFile = new File(sdCardDir, filename);
FileWriter fw = new FileWriter(CsvFile);
BufferedWriter bw = new BufferedWriter(fw);
rowCount = c.getCount();
colCount = c.getColumnCount();
if (rowCount > 0) {
c.moveToFirst();
for (i = 0; i < rowCount; i++) {
c.moveToPosition(i);
for (j = 0; j < colCount; j++) {
if (j != colCount - 1)
bw.write(c.getString(j) + ",");
else
bw.write(c.getString(j));
}
bw.newLine();
}
bw.flush();
}
} catch (Exception ex) {
Log.d("Exception","at export topic");
helperr.close();
ex.printStackTrace();
}
helperr.close();
c.close();
}
I am calling the function from here:
private View.OnClickListener clickHandler = new View.OnClickListener() {
#Override
public void onClick(View v) {
if (v.getId() == R.id.exportToDropBtn) {
try {
exportTopic();
}catch (Exception e){
Log.d("Exception","at export button");
e.printStackTrace();
}
}
Add code to create a file if it does not exist:
File dir = new File(Environment.getExternalStorageDirectory() + "/yourAppName");
// make them in case they're not there
dir.mkdirs();
File wbfile = new File(dir, fileName);
try {
if (!wbfile.exists()) {
wbfile.createNewFile();
}
// BufferedWriter for performance, true to set append to file flag
BufferedWriter buf = new BufferedWriter(
new FileWriter(wbfile, true));
buf.append(strBuilder.toString());
buf.newLine();
buf.close();
} catch(Exception e){
e.printStackTrace();
}
Here is the scenario:
1) create a file with input string=Sep 2015
2) Collect the drop down list into an array
3) if array equals string come out of loop else downloads new month report and overwrites txt file with new month name.
I tried below code, but I'm unable to implement the txt comparision part and txt overwrite part, please help.
driver.get("http://www.depreportingservices.state.pa.us/ReportServer/Pages/ReportViewer.aspx?%2fOil_Gas%2fOil_Gas_Well_Historical_Production_Report");
//maximizing the window
driver.manage().window().maximize();
List<WebElement> options;
int i = 0;
do
{
options = driver.findElement(By.id("ReportViewerControl_ctl04_ctl03_ddValue")).findElements(By.tagName("option"));
if(options.get(i).getText().equals("Sep 2015 (Unconventional wells)"))
{
System.out.println("old month");
break;
}
else
{ if (options.get(i).getText().equalsIgnoreCase("All" )){
System.out.println("Download new month");
WebElement identifier = driver.findElement(By.xpath(".//*[#id='ReportViewerControl_ctl04_ctl03_ddValue']"));
Select select1 = new Select(identifier);
//select1.selectByVisibleText("Oct");
select1.selectByVisibleText("Oct 2015 (Unconventional wells)");
Wait(20000);
driver.findElement(By.xpath(".//*[#id='ReportViewerControl_ctl04_ctl00']")).click();
Wait(70000);
//Click on File save button
driver.findElement(By.xpath(".//*[#id='ReportViewerControl_ctl05_ctl04_ctl00_Button']")).click();
//wait time to load the options
Wait(20000);
driver.findElement(By.xpath(".//*[#id='ReportViewerControl_ctl05_ctl04_ctl00_Menu']/div[2]/a")).click();
//fprofile.setPreference( "browser.download.manager.showWhenStarting", false );
//fprofile.setPreference( "pdfjs.disabled", true );
Wait(10000);
String str=options.get(2).getText();
System.out.println("str: " + str);
// driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
System.out.println("Oct month data downloaded in csv format");
//System.out.println("New month");
}
} } while (i++ < options.size());
}
Once try like this:
//Global Variable:
private WebDriver driver;
private String fileName = "/home/saritha/Desktop/MySeleniumFile.txt";
private File file;
In Tesng method:
#Test
public void oilGasTestng() throws InterruptedException {
driver.get("http://www.depreportingservices.state.pa.us/ReportServer/Pages/ReportViewer.aspx?%2fOil_Gas%2fOil_Gas_Well_Historical_Production_Report");
WebElement mSelectElement = driver
.findElement(By
.xpath("//select[#id='ReportViewerControl_ctl04_ctl03_ddValue']"));
List<WebElement> optionsList = mSelectElement.findElements(By
.tagName("option"));
for (int i = 2; i < optionsList.size(); i++) {
WebElement element = optionsList.get(i);
String newMonth = element.getText();
/*
* First we have read the data from file, if the file is empty then
* download the file and save the downloaded month(which is old
* month when v done with the downloading).
*/
String oldMonth = "";
if (i > 2) {
oldMonth = getTheOldMonthFromFile();
}
System.out.println("Old Month= " + oldMonth + " NewMonth= "
+ newMonth);
if (newMonth.equals(oldMonth)) {
// IF the string are same, nthng we need to do
} else if (!newMonth.equals(oldMonth)) {
/*
* If the string are not same,then i.e., considered as new
* Month, download the new month details
*/
element.click();
driver.findElement(
By.xpath(".//*[#id='ReportViewerControl_ctl04_ctl00']"))
.click();
System.out.println(newMonth
+ " month data downloaded in csv format");
saveIntoAFile(newMonth);
/*
* You can which is oldMonth which is new month, by unCommenting
* below condition
*/
// if (i == 4)
break;
}
}
}
//Save data into a file
private void saveIntoAFile(String oldMonth) {
BufferedWriter bw = null;
if (oldMonth != null) {
file = new File(fileName);
try {
if (!file.exists()) {
file.createNewFile();
}
Writer writer = new FileWriter(file);
bw = new BufferedWriter(writer);
bw.write(oldMonth);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bw != null) {
bw.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
//Get the oldMonth string from the file
private String getTheOldMonthFromFile() {
if (file == null && !file.exists()) {
return null;
}
String oldMonth = "";
StringBuffer strBuffer = new StringBuffer();
BufferedReader br = null;
java.io.FileReader reader = null;
try {
reader = new java.io.FileReader(file);
br = new BufferedReader(reader);
while ((oldMonth = br.readLine()) != null) {
strBuffer.append(oldMonth);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null) {
br.close();
}
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return strBuffer.toString();
}