how to acces other class method in java - java

I have two classes:
class actUI
public class ActUI extends javax.swing.JFrame{
//there are the other classes here
private static void writeToFile(java.util.List list, String path) {
BufferedWriter out = null;
try {
File file = new File(path);
out = new BufferedWriter(new FileWriter(file, true));
for (Object s : list) {
out.write((String) s);
out.newLine();
}
out.close();
} catch (IOException e) {
}
UniqueLineReader ULR = new UniqueLineReader();
ULR.setFileName(path);
}
//there are the other classes here
}
Class UniqueLineReader:
public class UniqueLineReader extends BufferedReader {
Set<String> lines = new HashSet<String>();
private Reader arg0;
public UniqueLineReader(Reader arg0) {
super(arg0);
}
#Override
public String readLine() throws IOException {
String uniqueLine;
while (lines.add(uniqueLine = super.readLine()) == false); //read until encountering a unique line
return uniqueLine;
}
public void setFileName(String filePath){
try {
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("test.txt");
UniqueLineReader br = new UniqueLineReader(new InputStreamReader(fstream));
String strLine;
// Read File Line By Line
PrintWriter outFile2 = new PrintWriter(new File("result.txt"));
String result = "";
List data = new ArrayList();
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println(strLine);
data.add(strLine);
}
writeToFile(data, "result.txt");
// Close the input stream
//in.close();
} catch (Exception e) {// Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
I want to acces UniqueLineReader from writeToFile method in actUI, but my code is not working, how can i do that with no error?, help me please.

Take a look at your code.
UniqueLineReader ULR = new UniqueLineReader(); // invalid constructor
ULR.setFileName(path);
There is no matching constructor for this. If you want to access writeToFile() from ActUI, Just change access modifier of writeToFile() to public now you can use following
UniqueLineReader.writeToFile(new ArrayList(), path);

Related

I have this csvReader java code and it is returning only the second line after the header over and over again till the last line index

I have this code:
public class ReadCSVFile {
public ArrayList<Efo> readFile(File file, Efo efo) {
ArrayList<Efo> efoList = new ArrayList<Efo>();
Logger log;
BufferedReader br = null;
try {
FileReader fr = new FileReader(file);
br = new BufferedReader(fr);
br.readLine();
String line=null;
while((line=br.readLine())!=null){
String[] csvEfo = line.split("\\|");
String midID = csvEfo[1];
String memID = csvEfo[2];
efo.setMidAppID(midID);
efo.setMidMemberID(memID);
efo = new Efo();
efoList.add(efo);
line = br.readLine();
}
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
} catch (IOException e) {
System.out.println(e.getMessage());
}
finally {
try {
if (br!= null) {
//flush and close both "input" and its underlying FileReader
br.close();
}
}
catch (IOException ex) {
ex.printStackTrace();
}
}
return efoList;
}
}
and I'm calling this arraylist here:
public class BEQ_Launcher extends CMSProcessBaseImpl{
BEQ_Launcher() {}
public void launchData(String appNode, boolean isOverride, boolean isCreateWI) {
try {
efo = new Efo();
csvInputFile = new ReadCSVFile();
csvContents = new ArrayList();
csvContents = csvInputFile.readFile(testFile, efo);
if(csvContents.size() > 0){
for (int i=0; i < csvContents.size(); i++) {
System.out.println(efo.getMidMemberID()","efo.getMidAppID());
}
}
other codes...
It is only outputting the line after the header over and over again..
What should i do?
When i remove the parameters in readFile and just declare Efo efo = new Efo inside the readFile.. getters are returning null when called..
Efo() class only have all the variable declarations and the getters and setters..
line = br.readLine();
You need to remove the final readLine() from this loop. Otherwise you will throw away every even-numbered line. while ((line = br.readLine()) != null) does all the line reading you need.

Odd output from file

I have an issue with the input I am getting from reading a file.
The file is made in another activity and is very simple:
ArrayList stuff = new ArrayList();
stuff.add("1,2,3");
try{
String saveFile = "saveGamesTest1.csv";
FileOutputStream saveGames = openFileOutput(saveFile, getApplicationContext().MODE_APPEND);
ObjectOutputStream save = new ObjectOutputStream(saveGames);
save.writeObject(stuff);
save.close(); }
In the other activity it's being read via
try {
FileInputStream fileIn=openFileInput("saveGamesTest1.csv");
InputStreamReader InputRead = new InputStreamReader(fileIn);
Scanner s = new Scanner(InputRead).useDelimiter(",");
System.out.println(s.next());
System.out.println(s.next());
System.out.println(s.next());
}
I was expecting (and hoping) to get a result back like
1
2
3
However, the result I'm getting is this:
/storage/emulated/0/Android/data/ys.test/files/saveGamesTest1.csv����sr��java.util.ArrayListx����a���I��sizexp������w������t��1
2
3x
What am I doing wrong?
.
EDIT
I tried Serializable as suggested below, like follow:
public class Save implements java.io.Serializable {
public String name;
public String address;
public transient int SSN;
public int number;
}
public void save(){
Save e = new Save();
e.name = "Reyan Ali";
e.address = "Phokka Kuan, Ambehta Peer";
e.SSN = 11122333;
e.number = 101;
try {
String saveFile = "save.ser";
FileOutputStream saveGames = openFileOutput(saveFile, getApplicationContext().MODE_APPEND);
ObjectOutputStream out = new ObjectOutputStream(saveGames);
out.writeObject(e);
out.close();
saveGames.close();
System.out.printf("Serialized data is saved in save.csv");
}
catch(IOException i) {
i.printStackTrace();
out.println("Save exception gepakt");
}
}
However, out.writeObject(e); gives an error saying that this isn't Serializable
You are not storing object as csv but as serialize java object you have to read as an object not as a csv file
take a look here https://www.tutorialspoint.com/java/java_serialization.htm
at Serializing an Object part
You have to use
FileInputStream in = null;
ObjectInputStream ois = null;
ArrayList stuff2 = null;
try {
in = openFileInput("saveGamesTest1.csv");
ois = new ObjectInputStream(in);
stuff2 = (ArrayList) ois.readObject();
} catch(IOException e) {...}
catch(ClassNotFoundException c) {...}
finally {
if (ois != null) {
ois.close();
}
if (in != null) {
in.close();
}
}
If you want a csv file you have to build it for instance by iterate over your array and write one by one the value in your file and adding the separator or follow this
How to serialize object to CSV file?
EDIT :
An elegant way in Java 7 to serialize an object (here a list like in your example) and deserialize :
public class Main {
public static void main(String[] args) {
List<Integer> lists = new ArrayList<>();
List<Integer> readList = null;
String filename = "save.dat";
lists.add(1);
lists.add(2);
lists.add(3);
//serialize
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filename))) {
oos.writeObject(lists);
} catch (IOException e) {
e.printStackTrace();
}
//don't need to close because ObjectOutputStream implement AutoCloseable interface
//deserialize
try (ObjectInputStream oos = new ObjectInputStream(new FileInputStream(filename))) {
readList = (List<Integer>) oos.readObject();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
//don't need to close because ObjectInputStream implement AutoCloseable interface
//test
if(!lists.equals(readList)) {
System.err.println("error list saved is not the same as the one read");
}
}
}

How do I write a code template for eclipse?

I have some specific code that I need, to be able to have certain I/O stuff that I don't want to write every time, and I just want to be able to add a java class so that it already has that code in there, I tried doing :
/*
ID: my_id
PROG: ${filename}
LANG: JAVA
*/
import java.util.*;
import java.io.*;
import java.net.InetAddress;
public class ${filename} {
static class InputReader {
private StringTokenizer st = null;
private BufferedReader br = null;
public InputReader(String fileName) throws Exception {
try {
br = new BufferedReader(new FileReader(fileName));
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
public InputReader(InputStream in) {
try {
br = new BufferedReader(new InputStreamReader(in), 32768);
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
public static void main(String[] args) throws Exception {
InetAddress addr = InetAddress.getLocalHost();
String hostname = addr.getHostName();
boolean isLocal = hostname.equals("paulpc");
String location = null;
InputReader in = null;
PrintWriter out = null;
if (!isLocal) {
location = ${filename}.class.getProtectionDomain().getCodeSource().getLocation().getPath();
in = new InputReader(location + "/" + "${filename}.in");
out = new PrintWriter(new FileWriter(location + "/" + "${filename}.out"));
} else {
in = new InputReader(System.in);
out = new PrintWriter(System.out);
}
solve(in, out);
out.close();
}
public static void solve(InputReader in, PrintWriter out) {
}
}
Basically this thing needs to be in xml, but I don't know how to write it properly, I thought writing ${filename} everywhere would do it, but it doesn't work. All in all, I want the name of the file to be written in places where I write "${filename}", how can I do it?
You can declare a template variable like this:
public class ${cursor}${type:newName} {
public ${type}() {
// constructor
}
}
Now if you use this as a template, both type occurrences will be updated by what you write when you edit it after template insertion.

Making Java I / O and change the file to split in java

I'm making a project where using java I / O
I have a file with the following data:
170631|0645| |002014 | 0713056699|000000278500
155414|0606| |002014 | 0913042385|000001220000
000002|0000|0000|00000000000|0000000000000000|000000299512
and the output I want is as follows:
170631
0645
002014
file so that the data will be decreased down
and this is my source code:
public class Tes {
public static void main(String[] args) throws IOException{
File file;
BufferedReader br =null;
FileOutputStream fop = null;
try {
String content = "";
String s;
file = new File("E:/split/OUT/Berhasil.RPT");
fop = new FileOutputStream(file);
br = new BufferedReader(new FileReader("E:/split/11072014/01434.RPT"));
if (!file.exists()) {
file.createNewFile();
}
while ((s = br.readLine()) != null ) {
for (String retVal : s.split("\\|")) {
String data = content.concat(retVal);
System.out.println(data.trim());
byte[] buffer = data.getBytes();
fop.write(buffer);
fop.flush();
fop.close();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
I want is to generate output as above from the data that has been entered
File Input -> Split -> File Output
thanks :)
I think you forgot to mention what problem are you facing. Just by looking at the code it seems like you are closing the fop(FileOutputStream) every time you are looping while writing the split line. The outputStream should be closed once you have written everything, outside the while loop.
import java.io.*;
public class FileReadWrite {
public static void main(String[] args) {
try {
FileReader inputFileReader = new FileReader(new File("E:/split/11072014/01434.RPT"));
FileWriter outputFileWriter = new FileWriter(new File("E:/split/11072014/Berhasil.RPT"));
BufferedReader bufferedReader = new BufferedReader(inputFileReader);
BufferedWriter bufferedWriter = new BufferedWriter(outputFileWriter);
String line;
while ((line = bufferedReader.readLine()) != null) {
for (String splitItem : line.split("|")) {
bufferedWriter.write(splitItem + "\n");
}
}
bufferedWriter.flush();
bufferedWriter.close();
bufferedReader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}

Android: Reading a text file and storing to an ArrayList<String>

So I am attempting to read from a file in android. I initialize everything yet I still get a NullPointerException. Am I missing something?
Error is recieved at line 25.
public class Read {
private ArrayList<String> contents;
private final String filename = "saves/user.txt";
public Read(Context context) {
try {
contents = new ArrayList<String>();
InputStream in = context.getAssets().open(filename);
if (in != null) {
// prepare the file for reading
InputStreamReader input = new InputStreamReader(in);
BufferedReader br = new BufferedReader(input);
String line = br.readLine();
while (line != null) {
contents.add(line);
}
in.close();
}else{
System.out.println("It's the assests");
}
} catch (IOException e) {
System.out.println("Couldn't Read File Correctly");
}
}
public ArrayList<String> loadFile() {
return this.contents;
}
}
Do like this
while ((line=reader.readLine()) != null)
{
contents.add(line);
}

Categories