I'm having some trouble writing an array list to file using printwriter. I've tried another way that worked but it wouldn't print all the things from the array list just one. This is the way I'm trying at the moment and it won't print anything.
datArrayList = new ArrayList<theAccounts>();
File file = new File("output.txt");
public void writer() throws FileNotFoundException, IOException{
PrintWriter pw = new PrintWriter(new FileOutputStream(file));
FileOutputStream fo = new FileOutputStream(file);
int datList = datArrayList.size();
for (int i = 0; i < datList; i++){
pw.write(datArrayList.get(i).toString() + "\n");
}
Can anyone tell me what i should be doing to write all the items in the array to the output file? thank you :)
datArrayList = new ArrayList<theAccounts>();
File file = new File("output.txt");
public void writer() throws FileNotFoundException, IOException {
FileOutputStream fo = new FileOutputStream(file);
PrintWriter pw = new PrintWriter(fo);
int datList = datArrayList.size();
for (theAccounts elem : datArrayList){
pw.println(elem);
}
pw.close();
fo.close();
}
Possibly because you weren't closing your streams, try:
datArrayList = new ArrayList<theAccounts>();
File file = new File("output.txt");
public void writer() throws FileNotFoundException, IOException {
try(PrintWriter pw = new PrintWriter(new FileOutputStream(file))){
int datList = datArrayList.size();
for (theAccounts s : datArrayList){
pw.println(s);
}
}
}
Here's the code that works. Need to flush/close streams in finally block.
package com.sto.sanbox;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
public class Accounts {
public class Account {
String name;
String amount;
public Account(String name, String amount) {
super();
this.name = name;
this.amount = amount;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
public String toString() {
return this.getName() + ", " + this.getAmount();
}
}
public void writer(ArrayList<Account> datArrayList) throws IOException {
PrintWriter pw = null;
FileOutputStream fo = null;
File file = null;
try {
file = new File("output.txt");
pw = new PrintWriter(new FileOutputStream(file));
fo = new FileOutputStream(file);
int datList = datArrayList.size();
for (int i = 0; i < datList; i++) {
pw.write(datArrayList.get(i).toString() + "\n");
}
} finally {
pw.flush();
pw.close();
fo.close();
}
}
public static void main(String args[]) {
Accounts Writer = new Accounts();
ArrayList<Account> datArrayList = new ArrayList<Account>();
Account account = Writer.new Account(" Name" , " 100000");
datArrayList.add(account);
try {
Writer.writer(datArrayList);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Some things to consider:
Closing your PrintWriter
Not making a second FileOutputStream called fo since this is unneeded
Making sure you're creating your file output.txt via file.newFile()
Related
I need to transfer a List between nodes and replace the existing one with the new one in the new node to achieve this, I'm using Sockets from Java.
I somehow have managed to transfer the data but only when I terminate the process. I need it to continue running, the process but at the same time transfer, the data in case any other new node joins the List.
How can I achieve this? I will have to introduce Threads in the Download along the road.
I got it working with files but now I need to change it to Sync lists, just having this is enough?
private static List<CloudByte> cloudByteList = Collections.synchronizedList(new ArrayList<>());
This is my current code:
import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import static FileData.getCloudByteList;
import static FileData.getFile;
public class FileData {
private static File file;
private static String fileName;
private static List<CloudByte> cloudByteList = Collections.synchronizedList(new ArrayList<>());
public FileData(String fileName) throws IOException {
if (fileName == null) {
this.fileName = "data2.bin";
this.file = new File(this.fileName);
Download.downloadFile();
} else {
this.file = new File(fileName);
this.fileName = fileName;
fillingList();
}
}
public void fillingList() throws IOException {
byte[] fileContents = Files.readAllBytes(file.toPath());
for (int i = 0; i < fileContents.length - 1; i++) {
cloudByteList.add(new CloudByte(fileContents[i]));
}
}
public static List<CloudByte> getCloudByteList() {
return cloudByteList;
}
public static File getFile() {
return file;
}
public String getFileName() {
return fileName;
}
public static void setFile(File file) {
FileData.file = file;
}
/*--------------------------Download--------------------------*/
}
class Download extends Thread {
static ConnectingDirectory connectingDirectory;
#Override
public void run() {
try {
downloadFile();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void downloadFile() throws IOException {
var nodes = ConnectingDirectory.getNodes();
Socket socket = null;
if (getFile().exists()) {
System.out.println("File: " + getFile() + " exists.");
new Upload().uploadFile();
}
FileOutputStream fos = new FileOutputStream(FileData.getFile());
//ObjectOutputStream oos = new ObjectOutputStream(fos);
for (int i = 0; i < nodes.size() - 1; i++) {
if (!(nodes.get(i).getHostPort() == ConnectingDirectory.getHostIP())) {
System.out.println("test33123");
ServerSocket serverSocket = new ServerSocket(nodes.get(i).getHostPort());
System.out.println(serverSocket);
socket = serverSocket.accept();
System.out.println("now socket");
System.out.println(socket);
//socket = new Socket(nodes.get(i).getName(), nodes.get(i).getHostPort());
//System.out.println(socket);
int bytes = 0;
DataInputStream ois = new DataInputStream(socket.getInputStream());
long size = ois.readLong();
System.out.println(size);
byte[] buffer = new byte[100 * 10000];
while (size > 0 && (bytes = ois.read(buffer, 0, (int) Math.min(buffer.length, size))) != -1) {
System.out.println("test3333");
fos.write(buffer, 0, bytes);
size -= bytes;
}
}
}
}
}
/*--------------------------Upload--------------------------*/
class Upload {
public void uploadFile() throws IOException {
int bytes = 0;
var nodes = ConnectingDirectory.getNodes();
FileInputStream fileInputStream = new FileInputStream("data.bin");
DataInputStream ois = new DataInputStream(fileInputStream);
if (!getFile().exists()) {
System.out.println("File doesn't exist." + "\nDownloading the file!");
new Download().downloadFile();
}
System.out.println("hello");
for (int i = 0; i < nodes.size() - 1; i++) {
System.out.println("hello2");
Socket socket = new Socket(nodes.get(i).getName(), nodes.get(i).getHostPort());
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
dos.writeLong(new File("data.bin").length());
byte[] buffer = new byte[100 * 10000];
while ((bytes = ois.read(buffer)) != -1) {
dos.write(buffer, 0, bytes);
dos.flush();
}
}
}
}
As you can see, I'm using DataInput because if I try to use the ObjectInputStream, I get a Corrupted Header Exception. I have more classes to add to this. My goal is as I said, to transfer the data inside the "data.bin" to a "data2.bin" file. I'm able to create it and delete it but at the same time, no Data is being written/sent to it.
How can I fix the CorruptedHeaderException and get it to send the content?
All help is appreciated.
StorageNode Class:
import java.io.IOException;
import java.util.Scanner;
import java.util.regex.Pattern;
import static FileData.*;
public class StorageNode extends Thread {
private static int serverPort = 8080;
private static int clientPort = 8082;
private static String fileName = null;
private static String addressName = "localhost";
private static ConnectingDirectory connectingDirectory;
private static FileData fileData;
static ErrorInjection errorInjection;
public static void main(String[] args) throws IOException, InterruptedException {
/* if (args.length > 3) {
addressName = args[0];
serverPort = Integer.parseInt(args[1]);
clientPort = Integer.parseInt(args[2]);
fileData = new FileData(args[3]);
} else {
fileName = null;
fileData = new FileData(fileName);
}*/
connectingDirectory = new ConnectingDirectory(addressName, clientPort, serverPort);
fileData = new FileData(fileName);
errorInjection = new ErrorInjection();
errorInjection.start();
if(fileData.getFile().exists()){
new Upload().uploadFile();
}else {
new Download().downloadFile();
}
}
ConnectingDirectory Class
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class ConnectingDirectory {
private String hostName;
private static int hostIP;
private int directoryIP;
private InetAddress address;
private InputStream in;
private OutputStream out;
private static List<Nodes> nodes = new ArrayList<>();
List<String> nodess = new ArrayList<>();
private Socket socket;
private String sign = "INSC ";
public ConnectingDirectory(String hostName, int hostIP, int directoryIP) throws IOException {
this.hostName = hostName;
this.hostIP = hostIP;
this.directoryIP = directoryIP;
this.address = InetAddress.getByName(hostName);
this.socket = new Socket(address, directoryIP);
signUp();
askConnectedNodes();
}
public void signUp() throws IOException {
System.out.println("You are connecting to the following address: " + hostIP + "\n");
System.out.println("The port you are connected to: " + socket.getPort() + "\n");
in = socket.getInputStream();
out = socket.getOutputStream();
out.write(generateSignUp(address, hostIP).getBytes());
out.flush();
}
public String generateSignUp(InetAddress address, int hostIP) {
String signUpString = sign + address + " " + hostIP + "\n";
return signUpString;
}
public void askConnectedNodes() throws IOException {
String directoryNodesAvailable;
String a = "nodes\n";
out.write(a.getBytes());
out.flush();
Scanner scan = new Scanner(in);
while (true) {
directoryNodesAvailable = scan.nextLine();
addExistingNodes(directoryNodesAvailable);
//System.out.println("Eco: " + directoryNodesAvailable);
if (directoryNodesAvailable.equals("end")) {
out.flush();
printNodes();
break;
}
}
}
public void addExistingNodes(String sta) throws IOException {
if (sta.equals("end")) return;
if (!(nodess.contains(sta))) {
nodess.add(sta);
nodes.add(new Nodes(nodess.get(nodess.size() - 1)));
}
return;
}
public static List<Nodes> getNodes() {
return nodes;
}
public void printNodes() {
System.out.println("Checking for available nodes: \n");
nodes.forEach((z) -> System.out.println(z.getNode()));
}
public Socket getSocket() {
return socket;
}
public static int getHostIP() {
return hostIP;
}
public InetAddress getAddress() {
return address;
}
}
For all of those that need help in the future:
Sender side:
Socket socket = new Socket("localhost", hostPort);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
ByteBlockRequest bbr = new ByteBlockRequest(getStoredData());
objectOutputStream.writeObject(bbr.blocksToSend(j));
Receiver side:
Socket = StorageNode.getServerSocket().accept();
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
byte[] bit = (byte[]) ois.readObject();
In my case, I needed to use byte[], so I had to do a few additional functions in the back, to change Cloudbyte[] into byte[]. Once I did that, I was able to send the data using, ObjectInput/ObjectOutput.
I'm getting a ClassCastException when I deserialize my object from a file. When I check the file the object is there, so I know it's being serialized correctly. For some reason the code breaks when trying to retrieve the object. The idea is to allow the user to check, by date, all the workouts they've recorded in their log. Also, I've tried implementing a comparator, but I kept getting the same error and I'm all out of ideas. Any help would be much appreciated.
Here is the code that is causing the trouble:
case Logger.CHECK_KEY:
//TODO
try {
workoutLog = (WorkoutLog) SerializationUtil.deserialize(file);
System.out.println("Deserializing from:..." + file.getName());
}
Here is the workoutLog class:
public class WorkoutLog implements Serializable{
public TreeMap < String , Workout > mWorkoutLog;
// thia is the actual Workoutlog
public WorkoutLog(){
mWorkoutLog = new TreeMap<>();
}
//the string key will be the workouts formatted date
public TreeMap < String, Workout> getWorkoutLog(){
return mWorkoutLog;
}
I'm including the body of the code for context
package com.alejandro;
import com.alejandro.Utilities.SerializationUtil;
import com.alejandro.model.Exercise;
import com.alejandro.model.Workout;
import com.alejandro.model.WorkoutLog;
import com.sun.istack.internal.NotNull;
import java.io.EOFException;
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
import java.util.TreeMap;
public class Logger {
public static final String COMPLETE_KEY = "COMPLETE";
public static final String INCOMPLETE_KEY = "INCOMPLETE";
public static final String ADD_KEY = "ADD";
public static final String CHECK_KEY = "CHECK";
public static final String EXIT_KEY = "EXIT";
public static void main(String[] args) throws IOException, ClassNotFoundException {
Logger logger = new Logger();
WorkoutLog workoutLog = new WorkoutLog();
Workout workout = new Workout();
File file = new File("workout.txt");
//im going to need to ask if the user wants to add a workout, close the program, or select a workout
String userInput = checkUserIntention();
//the switch statement goes through all the possible user inputs
switch(userInput){
case Logger.ADD_KEY:
printInstructions();
do{
logger.promptForExerciseData(workout);
}while(!checkIfUserIsDone());
workoutLog.getWorkoutLog().put(workout.getDate(),workout);
SerializationUtil.serialize(workoutLog,file);
System.out.println("Workout saved in..." +file.getName());
break;
case Logger.CHECK_KEY:
//TODO
try {
workoutLog = (WorkoutLog) SerializationUtil.deserialize(file);
System.out.println("Deserializing from:..." + file.getName());
System.out.println(workoutLog.getWorkoutLog().keySet()+"");
} catch(EOFException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}catch(ClassCastException E){
E.printStackTrace();
}
break;
case Logger.EXIT_KEY:
System.out.println("\nExiting program...");
break;
}
}
//I'm using this method to explain to the user how to use the program
protected static void printInstructions(){
System.out.println("\nWelcome to Mr.Strong!\n");
System.out.println("This program was developed to help powerlifters keep a log of their lifts.\n");
System.out.println("Because of this, the program will only recognize the following lifts:\n");
System.out.println("Squat, Bench, Deadlift, Press.\n");
System.out.println("The program is case-sensitive, make sure the information is entered as stated above.\n");
}
//this method asks the user for information about the lifts stores them in a workout object
//the methods used here are all organized throught the page, its just to keep things cleaner and separate
protected void promptForExerciseData(Workout workout){
Exercise exercise = new Exercise();
askForExerciseIdentity(exercise);
askForNumsRelLifts(exercise);
workout.getExerciseList().add(exercise);
}
//this will check to see if the user is done inputting the exercises he did, if he finished the program ends.
protected static boolean checkIfUserIsDone(){
Scanner scanner = new Scanner(System.in);
boolean isUserDone = false;
System.out.println("\nEnter: 'complete'" + ", if you are done. " +
"If not, enter:'incomplete " + ".\n");
String answer = scanner.nextLine();
if(answer.trim().toUpperCase().equals(Logger.COMPLETE_KEY)){
isUserDone = true;
} else if(answer.trim().toUpperCase().equals(Logger.INCOMPLETE_KEY)){
isUserDone = false;
} else{
checkIfUserIsDone();
}
return isUserDone;
}
//check if user wants to add, review, or close
protected static String checkUserIntention(){
String answer = "a";
Scanner scanner = new Scanner(System.in);
System.out.println("\nPlease choose an option:\n" +
"1-) Add a workout. Enter 'Add'.\n" +
"2-) Check a workout Enter 'Check'.\n" +
"3-) Exit the program. Enter 'Exit'\n");
answer = scanner.nextLine();
if(answer.trim().toUpperCase().equals(Logger.ADD_KEY) ||
answer.trim().toUpperCase().equals(Logger.CHECK_KEY)||
answer.trim().toUpperCase().equals(Logger.EXIT_KEY)){
return answer.toUpperCase();
}else{
System.out.println("Incorrect input.");
checkUserIntention();
}
return answer;
}
//all of this part is asking for the exercise data
//this is the part that asks for exercise id
protected void askForExerciseIdentity(Exercise exercise){
Scanner scanner = new Scanner(System.in);
do{
System.out.println("\nEnter a lift:\n");
String exerciseIdentity = scanner.nextLine();
if(exerciseIdentity.equals(exercise.SQUAT_KEY)){
exercise.setExerciseIdentity(exercise.SQUAT_KEY);
}else if(exerciseIdentity.equals(exercise.PRESS_KEY)){
exercise.setExerciseIdentity(exercise.PRESS_KEY);
}else if(exerciseIdentity.equals(exercise.BENCH_KEY)){
exercise.setExerciseIdentity(exercise.BENCH_KEY);
}else if(exerciseIdentity.equals(exercise.DEADLIFT_KEY)){
exercise.setExerciseIdentity(exercise.DEADLIFT_KEY);
}else {
exercise.setExerciseIdentity(null);
System.out.println("Please enter a valid exercise.");
}}while(exercise.getExerciseIdentity() == null);
}
//this is the part that aks for numbers
protected void askForNumsRelLifts(Exercise exercise){
exercise.setWeightUsed(askForWeightUsed());
exercise.setNumOfReps(askForNumOfReps());
exercise.setNumOfSets(askForNumOfSets());
}
protected double askForWeightUsed(){
Scanner scanner = new Scanner(System.in);
double weightUsed;
do{
try{
System.out.println("\nEnter weight used:\n");
weightUsed = Double.parseDouble(scanner.nextLine());
}catch(NumberFormatException e){
System.out.println("\nPlease enter a valid number\n");
weightUsed = 0;
}
} while(weightUsed == 0);
return weightUsed;
}
protected double askForNumOfSets(){
Scanner scanner = new Scanner(System.in);
double numOfSets;
do{
try{
System.out.println("\nEnter sets done:\n");
numOfSets = Double.parseDouble(scanner.nextLine());
}catch(NumberFormatException e){
System.out.println("\nPlease enter a valid number\n");
numOfSets = 0;
}
}while(numOfSets == 0);
return numOfSets;
}
protected double askForNumOfReps(){
Scanner scanner = new Scanner(System.in);
double reps;
do{
try{
System.out.println("\nEnter reps done:\n");
reps = Double.parseDouble(scanner.nextLine());
} catch(NumberFormatException e){
System.out.println("\nPlease enter a valid number\n");
reps = 0;
}
}while(reps == 0);
return reps;
}
}
Here is workout included:
public class Workout implements Serializable{
protected ArrayList<Exercise> mExerciseList;
protected Date mDateCreated;
public Workout(){
mExerciseList = new ArrayList<>();
mDateCreated = new Date();
}
public ArrayList<Exercise> getExerciseList(){
return mExerciseList;
}
public String getDate(){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
return sdf.format(mDateCreated);
}}
Here is the seralizationutil:
import com.alejandro.model.WorkoutLog;
import java.io.*;
public class SerializationUtil{
public static Object deserialize(File filename) throws IOException, ClassNotFoundException{
FileInputStream fis = new FileInputStream(filename);
Object obj = new Object();
BufferedInputStream bis = new BufferedInputStream(fis);
ObjectInputStream ois = new ObjectInputStream(bis);
while(fis.available()>0){
obj = ois.readObject();
}
ois.close();
return obj;
}
public static void serialize(Object object, File filename) throws IOException{
FileOutputStream fos = new FileOutputStream(filename);
BufferedOutputStream bos = new BufferedOutputStream(fos);
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(object);
oos.close();
}}
Here is what the compiler gives me:
java.lang.ClassCastException: java.lang.Object cannot be cast to com.alejandro.model.WorkoutLog
at com.alejandro.Logger.main(Logger.java:56)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
just try this simple example, i have modified your code extensively
one more thing, I dont know what implementation you have under SerializationUtil so i created my own implementation
My example works without any issue
package week4;
import java.io.Serializable;
import java.util.TreeMap;
public class WorkoutLog implements Serializable {
public TreeMap < String , Workout > mWorkoutLog;
// thia is the actual Workoutlog
public WorkoutLog(){
mWorkoutLog = new TreeMap<>();
}
//the string key will be the workouts formatted date
public TreeMap < String, Workout> getWorkoutLog(){
return mWorkoutLog;
}
}
package week4;
import java.io.Serializable;
public class Workout implements Serializable {
String date = "2016-01-13";
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
}
package week4;
import java.io.File;
import java.io.IOException;
public class TestWorkOut {
public static void main(String[] args) throws IOException, ClassNotFoundException {
WorkoutLog workoutLog = new WorkoutLog();
Workout workout = new Workout();
/* I had path to workout.txt as D:\\workout.txt*/
File file = new File("D:\\workout.txt");
workoutLog.getWorkoutLog().put(workout.getDate(),workout);
SerializationUtil.serialize(workoutLog,file);
System.out.println("Workout saved in..." +file.getName());
workoutLog = (WorkoutLog) SerializationUtil.deserialize(file);
System.out.println("Deserializing from:..." + file.getName());
System.out.println(workoutLog.getWorkoutLog().keySet()+"");
}
}
package week4;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class SerializationUtil {
public static void serialize(WorkoutLog workoutLog, File filename) {
FileOutputStream fos = null;
ObjectOutputStream out = null;
try {
fos = new FileOutputStream(filename);
out = new ObjectOutputStream(fos);
out.writeObject(workoutLog);
out.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static WorkoutLog deserialize(File filename) {
FileInputStream fis = null;
ObjectInputStream in = null;
WorkoutLog workout = null;
try {
fis = new FileInputStream(filename);
in = new ObjectInputStream(fis);
workout = (WorkoutLog) in.readObject();
in.close();
} catch (Exception ex) {
ex.printStackTrace();
}
return workout;
}
}
Output
Workout saved in...workout.txt
Deserializing from:...workout.txt
[2016-01-13]
I had to write a code to identify the language of tweets and to print out the tweets of a certain language. I have written the language identification part, but cannot get to print only the lines necessary.
Here is the code:
import java.io.*;
import java.util.*;
import weka.classifiers.bayes.NaiveBayes;
import weka.classifiers.functions.SMO;
import weka.classifiers.trees.RandomForest;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.converters.ConverterUtils.DataSource;
public class Lang_Detect
{
public static weka.classifiers.Classifier c;
public static HashMap<String,String> trigram=new HashMap<String,String>();
public static void initiate() throws Exception
{
c = loadModel("C:\\Users\\DIV\\ff\\Maithili\\nb.model"); // loads nb model
}
public static NaiveBayes loadModel(String path) throws Exception
{
NaiveBayes classifier;
FileInputStream fis = new FileInputStream(path);
ObjectInputStream ois = new ObjectInputStream(fis);
classifier = (NaiveBayes) ois.readObject();
ois.close();
return classifier;
}
public static void read_trigram()
{
try
{
FileInputStream fis = new FileInputStream("C:\\Users\\DIV\\ff\\Maithili\\Trigram.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fis,"UTF-8"));
String line;
while((line = br.readLine())!=null)
{
String words[]=line.split(":");
trigram.put(words[0].trim(), "");
}
fis.close();
}catch(IOException f){}
}
public static String feature_vector(String line)
{
String vector="";
String words[]=line.split(" ");
HashMap<String,String> local_word=new HashMap<String,String>();
for(int i=0;i<words.length;i++)
{
char ch[]=words[i].toCharArray();
for(int j=0;j<ch.length-2;j++)
{
local_word.put(ch[j]+""+ch[j+1]+""+ch[j+2], "");
}
}
for (Map.Entry<String, String> entry : trigram.entrySet())
{
if(local_word.containsKey(entry.getKey()))
{
vector+="1,";
}
else
{
vector+="0,";
}
}
return vector;
}
public static String lang_tag(String file) throws Exception
{
String tagged_sentence="";
int l=0,cntr=0;;
//String words[]=sentence.toLowerCase().split(" ");
StringBuffer str=new StringBuffer();
read_trigram();
// TODO Auto-generated method stub
int count=1;
str.append("#relation Language\n");
for (Map.Entry<String, String> entry : trigram.entrySet())
{
str.append("#attribute Trigram"+count+" numeric\n");
count++;
}
str.append("#attribute class {HN,NP,MT}\n");
str.append("#DATA\n");
try
{
FileInputStream fis = new FileInputStream(file);
BufferedReader br = new BufferedReader(new InputStreamReader(fis,"UTF-8"));
String line;
while((line = br.readLine())!=null)
{
str.append(feature_vector(line)+"?\n");
}
fis.close();
}catch(IOException f){}
Global.file_update("C:\\Users\\DIV\\ff\\Maithili\\HN_NP_MT_Unlabelled.arff", str.toString());
Instances unlabeled = new Instances(
new BufferedReader(
new FileReader("HN_NP_MT_Unlabelled.arff")));
// set class attribute
unlabeled.setClassIndex(unlabeled.numAttributes() - 1);
Instances labeled = new Instances(unlabeled);
// label instances
for (int i = 0; i < unlabeled.numInstances(); i++)
{
double clsLabel = c.classifyInstance(unlabeled.instance(i));
String tag="";
if(clsLabel==0.0)
tag="HN";
else if(clsLabel==1.0)
tag="NP";
else if(clsLabel==2.0)
{
tag="MT";
Global.file_append("C:\\Users\\DIV\\ff\\Maithili\\Detected_Maithili_Tweets.txt", tag);
}
System.out.println(tag);
}
return tagged_sentence.trim();
}
public static void main(String[] args) throws Exception
{
initiate();
lang_tag("C:\\Users\\DIV\\ff\\Maithili\\tweets.txt");
}
}
As you can see in the lang_tag(), I want to print the lines which are tagged as MT, But I cannot get the lines in any particular variable.
Can someone help me?
Serializing data through
try {
FileOutputStream fileOut = new FileOutputStream(
"C:\\Users\\saikiran\\Documents\\NetBeansProjects\\FTP\\reg.ser", true);
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(r);
out.close();
fileOut.close();
System.out.printf("Serialized data is saved in /tmp/reg.ser");
pr.println("Registered Successfully ");
} catch (IOException i) {
i.printStackTrace();
}
and while Deserializing not getting entire file objects only getting single object i.e starting object only .
FileInputStream fileIn = new FileInputStream("C:\\Users\\saikiran\\Documents\\NetBeansProjects\\FTP\\reg.ser");
ObjectInputStream in = null;
while (fileIn.available() != 0) {
in = new ObjectInputStream(fileIn);
while (in != null && in.available() != 0) {
r = (Registration) in.readObject();
System.out.println("Logged in :" + "User name :" + r.u + "Password " + r.p);
if (r.u.equals(ur) && r.p.equals(ps)) {
System.out.println("Logged in :" + "User name :" + r.u + "Password " + r.p);
pr.println("Display");
}
}
}
I have created the working sample for you .
My POJO serializable class will be ,
import java.io.Serializable;
public class Pojo implements Serializable{
String name;
String age;
String qualification;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getQualification() {
return qualification;
}
public void setQualification(String qualification) {
this.qualification = qualification;
}
}
My main class will be,
import java.io.EOFException;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;
public class Serialization {
/**
* #param args
*/
public static final String FILENAME = "F:\\test\\cool_file.ser";
public static void main(String[] args) throws IOException, ClassNotFoundException {
FileOutputStream fos = null;
//ObjectOutputStream oos = null;
try {
fos = new FileOutputStream(FILENAME);
//oos = new ObjectOutputStream(fos);
/* for (String s : test.split("\\s+")) {
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(s);
}*/
for(int i=0;i<10;i++){
ObjectOutputStream oos = new ObjectOutputStream(fos);
Pojo pojo = new Pojo();
pojo.setName("HumanBeing - "+i);
pojo.setAge("25 - "+i);
pojo.setQualification("B.E - "+i);
oos.writeObject(pojo);
}
} finally {
if (fos != null)
fos.close();
}
List<Object> results = new ArrayList<Object>();
FileInputStream fis = null;
//ObjectInputStream ois = null;
try {
fis = new FileInputStream(FILENAME);
//ois = new ObjectInputStream(fis);
while (true) {
ObjectInputStream ois = new ObjectInputStream(fis);
results.add(ois.readObject());
}
} catch (EOFException ignored) {
// as expected
} finally {
if (fis != null)
fis.close();
}
System.out.println("results = " + results);
for (int i=0; i<results.size()-1; i++) {
System.out.println(((Pojo)results.get(i)).getName()+ " "+((Pojo)results.get(i)).getAge()+ " "+((Pojo)results.get(i)).getQualification());
}
}
}
Hope it helps.
i am having a program in java.which system.out some strings,i need to save each of them in a text file
it is showing in a format
ruo1 row2 row3
i want it in
row1
row2
row3
how can i do that in java?
import java.util.Arrays;
import java.io.*;
public class BruteForce {
public static FileOutputStream Output;
public static PrintStream file;
public static String line;
public static void main(String[] args) {
String password = "javabeanc";
char[] charset = "abcdefghijklmnopqrstuvwxyz".toCharArray();
BruteForce bf = new BruteForce(charset, 8);
String attempt = bf.toString();
while (true) {
FileWriter writer;
try {
writer = new FileWriter("test.txt");
writer.write(attempt+"\n");
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
attempt = bf.toString();
System.out.println("Tried: " + attempt);
bf.increment();
}
}
private char[] cs; // Character Set
private char[] cg; // Current Guess
public BruteForce(char[] characterSet, int guessLength) {
cs = characterSet;
cg = new char[guessLength];
Arrays.fill(cg, cs[0]);
}
public void increment() {
int index = cg.length - 1;
while(index >= 0) {
if (cg[index] == cs[cs.length-1]) {
if (index == 0) {
cg = new char[cg.length+1];
Arrays.fill(cg, cs[0]);
break;
} else {
cg[index] = cs[0];
index--;
}
} else {
cg[index] = cs[Arrays.binarySearch(cs, cg[index]) + 1];
break;
}
}
}
public String toString() {
return String.valueOf(cg);
}
}
Very quick code. I apologize if there are compile errors.
import java.io.FileWriter;
import java.io.IOException;
public class TestClass {
public static String newLine = System.getProperty("line.separator");
public static void main(String[] a) {
FileWriter writer;
try {
writer = new FileWriter("test.txt");
for(int i=0;i<3;i++){
writer.write(row+i+newLine);
}
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
how about adding a new line character "\n" to each row ?
u can use PrintWriter pw;
pw.println(row+i)
in above instead of hard coding newLine
Using JDK 11 one can write:
public void writeToFile() {
String content = "Line 1\nLine 2";
Path path = Paths.get("./resources/sample-new.txt");
Files.writeString(path, content);
}