Why can't i display the output on the text file? - file

Im doing a input output file handling in java,my code is not displaying the output i put in and whether i open with the SampleOutputText.txt it does not show anything.Can someone show me why?
import java.io.*;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Scanner;
public class OutputFile
{
static PrintWriter outputFile;
static Scanner inputFile;
public static void main(String[] args) throws Exception, IOException
{
String[] words=null;
int wc=0;
inputFile = new Scanner(new FileReader("../fileSample2/src/fileSample2/SampleText.txt"));
File file = new File("../fileSample2/src/fileSample2/SampleText.txt");
outputFile = new PrintWriter("../fileSample2/src/fileSample2/SampleOutputText.txt");
//number of words
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String s;
while((s=br.readLine())!=null)
{
words=s.split(" ");
wc=wc+words.length;
}
fr.close();
//length
outputFile.println("length: " + file.length());
//path
Path path = Paths.get("../fileSample2/src/fileSample2/SampleText.txt");
outputFile.println("Specific Path: " + path);
outputFile.println("Number of words: " + wc);
}
}

Related

Send .dex file via post request android studio

For my own purposes, I want to send other app's dex file to a remote server and get the answer.
I've used answers that I found here. I tried to create a simple example at first, just to connect to the server and upload the dex file. So far I haven't managed to extract dex from other apps , so I thought of using a dex file I already have.
As I've read, not common files should be stored either to "/res/raw" or "assets"
I tried many ways to load it as a File but none of them worked . The path I used in all cases were found in right click on file -> copy reference.
create a res folder under /raw and
File f = new File("res/raw/filename.dex");
Create a new assets folder under /app
File f = new File("filename.dex");
Create assets folder under /main
File f = new File("main/assets/filename.dex");
and so on.
The only way I managed to do so is by using InputStream
Inputstream in = getResources().openRawResources(R.raw.filename_without_dex)
but I couldn't cast it to File, so I dropped this solution.I want to have it as a File cause the following POST request must be a multipart/form.
In java, the way to "load" a file is straightforward. Why not in android ?
A truly ugly, quick and dirty solution.
No error check or cleanup.
But it works.
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
public class MainActivity extends ActionBarActivity {
final String TAG = "GetDex";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getAppPaths(); // to list all packages
String s = "/data/app/SoftKeyboard/SoftKeyboard.apk"; // a sample package
byte[] b = getFile(s);
byte[] dex = unzipDex(b, s);
Log.d(TAG, String.format("DEX size is %d", dex.length));
}
List<String> getAppPaths() {
final PackageManager pm = getPackageManager();
//get a list of installed apps.
List<ApplicationInfo> packages = pm.getInstalledApplications(PackageManager.GET_META_DATA);
List<String> paths = new ArrayList<>();
for (ApplicationInfo packageInfo : packages) {
Log.d(TAG, "Installed package :" + packageInfo.packageName);
Log.d(TAG, "Apk file path:" + packageInfo.sourceDir);
paths.add(packageInfo.sourceDir);
}
return paths;
}
byte[] getFile(String filename) {
try {
RandomAccessFile f = new RandomAccessFile(filename, "r");
byte[] b = new byte[(int)f.length()];
f.readFully(b);
return b;
} catch(IOException exception) {
exception.printStackTrace();
}
return null;
}
public byte[] unzipDex(byte[] bytes, String filename) {
try{
ZipFile zipFile = new ZipFile(filename);
ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream(bytes));
ZipEntry ze = zis.getNextEntry();
while(ze!=null){
String entryName = ze.getName();
if(!entryName.equals("classes.dex")) {
ze = zis.getNextEntry();
continue;
}
InputStream is = zipFile.getInputStream(ze);
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int nRead;
byte[] data = new byte[16384];
while ((nRead = is.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, nRead);
}
buffer.flush();
return buffer.toByteArray();
}
System.out.println("Done");
}catch(IOException ex){
ex.printStackTrace();
}
return null;
}
}

how to export and import realm data in android

I know there are those questions which are similar to mine have already raised.
However, I can not go further more on some point.
** I can not copy file on below.-> realm.writeCopyTo(exportRealmFile);
** The code that I referred to is below.
https://stackoverflow.com/a/36324183/6650123
And let me share my application class which I defaulted Realm.
Wondering if the realm file can not be copied because of that..
Would you take a look and advise?
**
public class MyApplication extends Application {
private static MyApplication singleton;
private RealmConfiguration realmConfig;
String TAG=getClass().getName();
public static MyApplication getSingleton(){;
return singleton;
}
public void onCreate() {
super.onCreate();
singleton=this;
// Create the Realm configuration
realmConfig = new RealmConfiguration.Builder(this).build();
Realm.setDefaultConfiguration(realmConfig);
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
public void onLowMemory() {
super.onLowMemory();
}
public void onTerminate() {
super.onTerminate();
}
}
// my codes for backup realm
package com.first.project;
import android.content.Context;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import io.realm.Realm;
public class RealmBackupRestore {
private final static String TAG = RealmBackupRestore.class.getName();
private Context context;
private Realm realm;
public RealmBackupRestore(Context context) {
realm= Realm.getDefaultInstance();
//this.realm = Realm.getInstance(BaseApplication.realmConfiguration);
this.context = context;
}
public void backup() {
Log.d(TAG, "realm은"+realm);
Log.d(TAG, "Realm.getDefaultInstance();은"+Realm.getDefaultInstance());
File exportRealmFile = null;
File exportRealmPATH = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
Log.d(TAG, "exportRealmPATH"+exportRealmPATH);
String exportRealmFileName = "aa.realm";
Log.d(TAG, "Realm DB Path = " + realm.getPath());
try {
// create a backup file
exportRealmFile = new File(exportRealmPATH, exportRealmFileName);
// if backup file already exists, delete it
exportRealmFile.delete();
// copy current realm to backup file
realm.writeCopyTo(exportRealmFile);
} catch (IOException e) {
e.printStackTrace();
}
String msg = "File exported to Path: " +Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
Toast.makeText(context, msg, Toast.LENGTH_LONG).show();
Log.d(TAG, msg);
realm.close();
}
public void restore() {
//Restore
File exportRealmPATH = context.getExternalFilesDir(null);
String FileName = "default.realm";
String restoreFilePath = context.getExternalFilesDir(null) + "/" + FileName;
Log.d(TAG, "oldFilePath = " + restoreFilePath);
copyBundledRealmFile(restoreFilePath, FileName);
Log.d(TAG, "Data restore is done");
}
private String copyBundledRealmFile(String oldFilePath, String outFileName) {
try {
File file = new File(context.getFilesDir(), outFileName);
Log.d(TAG, "context.getFilesDir() = " + context.getFilesDir().toString());
FileOutputStream outputStream = new FileOutputStream(file);
FileInputStream inputStream = new FileInputStream(new File(oldFilePath));
byte[] buf = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buf)) > 0) {
outputStream.write(buf, 0, bytesRead);
}
outputStream.close();
return file.getAbsolutePath();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private String dbPath() {
return realm.getPath();
}
}

JFreeChart "real-time" line graph with two lines

I am using JFreeChart to display data gathered from two sensors on an arduino using RXTX in "real-time". There is two values separated by a comma being sent from the arduino. I can successfully plot the data from one sensor on the graph but I am unable to add a second line for the data from the second sensor. Do anyone know how I can add the second line to the graph ?
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import javax.swing.BorderFactory;
import javax.swing.JPanel;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.DateAxis;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.plot.CombinedDomainXYPlot;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.StandardXYItemRenderer;
import org.jfree.data.time.Millisecond;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
import org.jfree.ui.ApplicationFrame;
import org.jfree.ui.RefineryUtilities;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Enumeration;
import javax.swing.JOptionPane;
public class respiratorytest2 extends javax.swing.JFrame implements SerialPortEventListener {
public static float[][] C_A_Data = new float[120][2];
public static int count = 0;
public static respiratorytest2 demo;
public static float[ ]dataArray = new float[600];
public float data1;
public float data2;
public static Connection conn;
public static PreparedStatement stmt = null;
public static String sql;
public static int result=0;
public static int result2;
public static String gusername;
/**
* The number of subplots.
*/
public static final int SUBPLOT_COUNT = 3;
/**
* The datasets.
*/
private TimeSeriesCollection[] datasets;
/**
* The most recent value added to series 1.
*/
private double[] lastValue = new double[SUBPLOT_COUNT];
private double[] lastValue2 = new double[SUBPLOT_COUNT];
SerialPort serialPort;
/**
* The port we're normally going to use.
*/
private static final String PORT_NAMES[] = {
"/dev/tty.usbserial-A9007UX1", // Mac OS X
"/dev/ttyUSB0", // Linux
"COM3", // Windows
};
/**
* A BufferedReader which will be fed by a InputStreamReader converting the
* bytes into characters making the displayed results codepage independent
*/
private BufferedReader input;
/**
* The output stream to the port
*/
private OutputStream output;
/**
* Milliseconds to block while waiting for port open
*/
private static final int TIME_OUT = 2000;
/**
* Default bits per second for COM port.
*/
private static final int DATA_RATE = 9600;
public static void visibility(){
demo.setVisible(true);
}
public respiratorytest2(String title) {
super(title);
initialize();
final CombinedDomainXYPlot plot = new CombinedDomainXYPlot(new DateAxis("Time (sec)"));
this.datasets = new TimeSeriesCollection[SUBPLOT_COUNT];
this.lastValue[0] = 100.0;
this.lastValue2[0] = 100.0;
final TimeSeries series = new TimeSeries("Volume ", Millisecond.class);
final TimeSeries series2 = new TimeSeries("Volume ", Millisecond.class);
this.datasets[0] = new TimeSeriesCollection(series);
this.datasets[1] = new TimeSeriesCollection(series2);
final NumberAxis rangeAxis = new NumberAxis("Volume");
rangeAxis.setAutoRangeIncludesZero(false);
final XYPlot subplot = new XYPlot(
this.datasets[0], null, rangeAxis, new StandardXYItemRenderer()
);
subplot.setBackgroundPaint(Color.lightGray);
subplot.setDomainGridlinePaint(Color.white);
subplot.setRangeGridlinePaint(Color.white);
plot.add(subplot);
final JFreeChart chart = new JFreeChart("Respiratory Test", plot);
chart.setBorderPaint(Color.black);
chart.setBorderVisible(true);
chart.setBackgroundPaint(Color.white);
plot.setBackgroundPaint(Color.lightGray);
plot.setDomainGridlinePaint(Color.white);
plot.setRangeGridlinePaint(Color.white);
final ValueAxis axis = plot.getDomainAxis();
axis.setAutoRange(true);
axis.setFixedAutoRange(60000.0); // 60 seconds
final JPanel content = new JPanel(new BorderLayout());
final ChartPanel chartPanel = new ChartPanel(chart);
content.add(chartPanel);
final JPanel buttonPanel = new JPanel(new FlowLayout());
content.add(buttonPanel, BorderLayout.SOUTH);
chartPanel.setPreferredSize(new java.awt.Dimension(500, 470));
chartPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
setContentPane(content);
}
public void initialize() {
CommPortIdentifier portId = null;
Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();
//First, Find an instance of serial port as set in PORT_NAMES.
while (portEnum.hasMoreElements()) {
CommPortIdentifier currPortId = (CommPortIdentifier) portEnum.nextElement();
for (String portName : PORT_NAMES) {
if (currPortId.getName().equals(portName)) {
portId = currPortId;
break;
}
}
}
if (portId == null) {
System.out.println("Could not find COM port.");
return;
}
try {
// open serial port, and use class name for the appName.
serialPort = (SerialPort) portId.open(this.getClass().getName(),
TIME_OUT);
// set port parameters
serialPort.setSerialPortParams(DATA_RATE,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
// open the streams
input = new BufferedReader(new InputStreamReader(serialPort.getInputStream()));
output = serialPort.getOutputStream();
// add event listeners
serialPort.addEventListener(this);
serialPort.notifyOnDataAvailable(true);
} catch (Exception e) {
System.err.println("Exception=" + e.toString());
}
}
/**
* This should be called when you stop using the port. This will prevent
* port locking on platforms like Linux.
*/
public synchronized void close() {
if (serialPort != null) {
serialPort.removeEventListener();
serialPort.close();
}
}
/**
* Handle an event on the serial port. Read the data and print it.
*/
#Override
public synchronized void serialEvent(SerialPortEvent oEvent) {
int i=0,j=0,a,b;
StringBuffer sq = new StringBuffer();
java.util.Date utilDate = new java.util.Date();
java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
try {
String inputLine = input.readLine();
System.out.println(inputLine);
String[] dArray = inputLine.split(",");
data1 = Float.valueOf(dArray[0]);
data2 = Float.valueOf(dArray[1]);
this.lastValue[0] = new Integer(dArray[0]).intValue();
this.lastValue2[0] = new Integer(dArray[1]).intValue();
//this.datasets[0].getSeries(0).add(new Millisecond(), this.lastValue[0]);
//this.datasets[1].getSeries(0).addOrUpdate(new Millisecond(),this.lastValue2[0]);
sq.append ("INSERT INTO U_DATA");
sq.append("(USERNAME, SESSION_NUM, SESSION_DATE, CHEST_DATA, ABDOMINAL_DATA) ");
sq.append("VALUES ( ");
sq.append("?, ?, ?, ?, ?");
sq.append(")");
System.out.println("Creating statement...");
try {
//stmt = conn.createStatement();
stmt = conn.prepareStatement(sq.toString());
stmt.setString(1, gusername);
stmt.setInt(2, result2);
stmt.setDate(3, sqlDate);
stmt.setFloat(4, data1);
stmt.setFloat(5, data2);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
result = stmt.executeUpdate();
count = count + 1;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//STEP 6: Clean-up environment
try {
stmt.close();
} catch (SQLException e) {
}
if (count == 400){
JOptionPane.showMessageDialog(null,"You Have Successfully Completed The Test");
conn.close();
report.main(gusername);
setVisible(false);
//dispose();
close();
//respiratorytest.successicon();
}
} catch (Exception e) {
System.err.println("Exception serialEvent=" + e.toString());
}
}
// Ignore all the other eventTypes, but you should consider the other ones.
}
public static void main(String username) throws Exception {
gusername = username;
conn = DBman.main();
Statement stmt2 = null;
sql = "SELECT COUNT(DISTINCT SESSION_NUM) AS rnum FROM U_DATA WHERE USERNAME='"+gusername+"'";
ResultSet rs;
try {
stmt2 = conn.createStatement();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
rs = stmt2.executeQuery(sql);
rs.next();
result2 = rs.getInt("rnum");
result2 = result2 + 1;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
demo = new respiratorytest2("Respiratory Test");
demo.pack();
RefineryUtilities.centerFrameOnScreen(demo);
demo.setVisible(false);
}
}
You can add a second series to the chart, as shown here using TimeSeriesCollection:
or here using DynamicTimeSeriesCollection:
Use java.swing.Timer to poll the serial port periodically or a SwingWorker to query the serial port in the background, as shown here and here.

write output in new file using buffer writter

Output of this program I want to write in new file.so how can I generate new file like xls. or other and write the results in it.
I had already read the file then applied kmean clustering algorithm and generate output now I want to write that.
package kmean;
//package greenblocks.statistics;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import weka.clusterers.SimpleKMeans;
import weka.core.Instances;
/**
*
* #author admin
*/
public class Kmean {
public static BufferedReader readDataFile(String filename) {
BufferedReader inputReader = null;
try {
inputReader = new BufferedReader(new FileReader(filename));
} catch (FileNotFoundException ex) {
System.err.println("File not found: " + filename);
}
return inputReader;
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException, Exception {
SimpleKMeans kmeans = new SimpleKMeans();
kmeans.setSeed(10);
//important parameter to set: preserver order, number of cluster.
kmeans.setPreserveInstancesOrder(true);
kmeans.setNumClusters(5);
BufferedReader datafile = readDataFile("elecNormNew.arff");
// BufferedReader datafile = readDataFile("perturbed.csv");
Instances data = new Instances(datafile);
kmeans.buildClusterer(data);
// This array returns the cluster number (starting with 0) for each instance
// The array has as many elements as the number of instances
int[] assignments = kmeans.getAssignments();
int i=0;
for(int clusterNum : assignments) {
System.out.printf("Instance %d -> Cluster %d \n", i, clusterNum);
i++;
}
// TODO code application logic here
}
}
use this code to write your output in new text file... may this will help you
package com.mkyong;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class WriteToFileExample {
public static void main(String[] args) {
try {
String content = "This is the content to write into file";
File file = new File("/filePath/filename.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
}
}

I am trying to get a file to read in to an Array list but im havin some troubles

I am trying to get a file to read into an Arraylist, read me back the numbers in the file and calculate the average of the numbers is the file. I have tried several different types of code but have had no success. here is my code. IF anyone could please just tell me what the code has wrong with it and show me how to fix it i would greatly appreciate it.
import java.io.BufferedReader;
import java.io.File;
//import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
//import java.io.InputStreamReader;
import java.util.ArrayList;
//import java.util.List;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
public class Week07 {
public static void main(String []args) throws IOException
{
JFileChooser chooser = new JFileChooser();
int a = chooser.showOpenDialog(null);
//check result
File file = null;
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
file = chooser.getSelectedFile();
}
return;
}
File file;
ArrayList<String> values = new ArrayList<String>();{
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String text = null;
while ((text = br.readLine()) != null) {
values.add(text);
}
} catch (IOException exp) {
exp.printStackTrace();}
JOptionPane.showMessageDialog(null, "The Numbers are :" + values);
}}
You are returning after the file is choosed, check the return in the code below
File file = null;
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
file = chooser.getSelectedFile();
}
return;
change that code do this:
File file = null;
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
file = chooser.getSelectedFile();
}
if(file==null){
return;//only return if no file was choosed
}

Resources