I am trying to save text and int value in a binary file but it is not working as expected.
This is my code.
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.util.Scanner;
import java.io.InputStreamReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.FilterOutputStream;
import java.io.FileOutputStream;
import java.util.Random;
public class Test{
public static void main(String[] args) throws FileNotFoundException, IOException {
Scanner input=new Scanner(System.in);
System.out.println("Enter first name of doctor : ");
String fn=input.next();
System.out.println("enter middle name of doctor : ");
String mn=input.next();
FileOutputStream os=new FileOutputStream("Doctorsdata.txt");
DataOutputStream file=new DataOutputStream(os);
file.writeUTF(fn.trim());
file.writeUTF(mn.trim());
FileInputStream osb=new FileInputStream("Doctorsdata.txt");
DataInputStream osa=new DataInputStream(osb);
System.out.println("a "+osa.readUTF());
System.out.println("b "+osa.readUTF());
file.close();
}
}
This is my input
fn mn Output
abc def ̀a扡c搃晥
abc defg abc defg
If i write fn and mn as of same length it will work and if they are of not same length it will not work like above. Also if I have a 3rd variable of type byte and i will write like file.writeByte(age); in first input's case it will not work.
What am I doing wrong?
Thanks.
Related
I am trying to convert a .prn file to html. But due to file format, I am not able to parse in a way I want.
I tried many approaches. some of are:
package main;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class PrnToHtml {
public static void main(String[] args) {
try (BufferedReader reader = new BufferedReader(new FileReader(".\\Workbook2.prn"));
FileWriter writer = new FileWriter("output_prn.html")) {
writer.write("<html><body><h3>PRN to HTML</h3><table border>\n");
String currentLine;
while ((currentLine = reader.readLine()) != null) {
writer.write("<tr>");
for(String field: currentLine.split("\\s{2,}")) // "\\s{2,}"
writer.write("<td>" + field + "</td>");
writer.write("</tr>\n");
}
writer.write("</table></body></html>\n");
} catch (IOException e) {
e.printStackTrace();
}
}
}
Output of this will be html page looks like this:
prn file\data looks like this:
Other this I tried to read this is:
package main;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class PRNToHtml {
private static final String DILIM_PRN = " ";
private static final Pattern PRN_SPLITTER = Pattern.compile(DILIM_PRN);
public static void main(String[] args) throws URISyntaxException, IOException {
try (#SuppressWarnings("resource")
Stream<String> lines = new BufferedReader(new FileReader(".\\Workbook2.prn")).lines()) {
List<String[]> inputValuesInLines = lines.map(l -> PRN_SPLITTER.split(l)).collect(Collectors.toList());
for (String[] strings : inputValuesInLines) {
for (String s : strings) {
System.out.print(s.replaceAll("\\s+", "") + " ");
}
System.out.println();
}
}
}
}
output of this is the exactly same looking in prn data file. But when I am trying to embed in html, it is looking weird like this:
Help will be appreciated.
Thank you :)
Essentially I need to create a anagram program to filter out the specific characters I input using a scanner from a dictionary file. Example, if I enter 'Stop' the result would be "tops spot pots" etc
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
import java.util.stream.Stream;
public class Anagram1 {
public static void main(String[] args) throws IOException {
new Anagram1().doIt();
}
private void doIt() throws IOException {
Scanner scanner = new Scanner(System.in);
while (true) {
String theWord = scanner.next();
if (theWord.equals("999")) {
scanner.close();
break;
}
ISinglyLinkedList<String> anagrams = listAnagrams(theWord);
anagrams.forEach(System.out::print);
}
}
private ISinglyLinkedList<String> listAnagrams(final String theWord) throws
IOException {
Stream<String> dict = Files.lines(Paths.get("Data", "pocket.dic"));
ISinglyLinkedList<String> theList = dict
.collect(Util.toSinglyLinkedList())
//Add a filter and a forEach to print the specific words you wanna print
;
dict.close();
return theList;
}
}
So far the program only gives me enter code here every single word in the dictionary. Is there a way to filter out only the words that share the same letter?
You could use the fact that two words are anagrams if after sorting they are the same:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Anagram1 {
public static void main(String[] args) throws IOException {
Map<String, List<String>> anagramsMap = new HashMap<>();
try (Stream<String> dict = Files.lines(Paths.get("Data", "pocket.dic"))) {
dict.forEach(w -> anagramsMap.computeIfAbsent(getSortedWord(w), x -> new ArrayList<>()).add(w));
}
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.print("Enter a word to get its anagrams or 999 to exit: ");
String word = scanner.next();
if (word.equals("999")) {
break;
}
List<String> anagrams = anagramsMap.get(getSortedWord(word.toLowerCase()));
System.out.println(String.join(" ", anagrams));
}
}
public static String getSortedWord(String word) {
return Stream.of(word.split("")).sorted().collect(Collectors.joining());
}
}
Example Usage:
Enter a word to get its anagrams or 999 to exit: Stop
post pots spot stop tops
Enter a word to get its anagrams or 999 to exit: 999
I'm working on resume parser and i can get some of data i.e company details from text but not getting if it is kept in a grid or table
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JOptionPane;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
public class CmpnyNameex {
public static void main(String[] args)throws IOException {
String text="";
String name="";
XWPFDocument msDocx = new XWPFDocument(new FileInputStream("A:\\Resumes\\Anwesh.docx"));
XWPFWordExtractor extractor = new XWPFWordExtractor(msDocx);
text = extractor.getText();
}
catch(FileNotFoundException ex){ex.printStackTrace();
JOptionPane.showMessageDialog(null,"The system cannot find the file specified file it may be because of old file format","Error",JOptionPane.ERROR_MESSAGE);
}
String rx13="(?<=Have been associated with).*.(.*Ltd?)";
Pattern p1 = Pattern.compile(rx13);
Matcher found1 = p1.matcher(text);
while(found1.find())
{
name= found1.group(0);
}
}
}
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class running{
public static void main(String args[]) throws IOException {
double sum=0.0;
double num=0.0;
FileReader fin = (new File("running.txt");
Scanner src = new Scanner(fin);
while (src.hasNext()){
if(src.hasNextDouble()){
num=src.nextDouble();
sum=sum+num;
System.out.println(sum);
}else{
break;
}
}
fin.close();
}
}
Around the Scanner portion I cant seem to fix the error.
It says File cant be resolved to a type.
And the file cant be found.
You are missing an import java.io.File; statement. Since you did not import this class (and since your code is not located in the java.io package), Java can't recognize it.
You have a type in your code. You code should be:
FileReader fin = new FileReader(new File("running.txt"));
^^^^^^^^^^^^^^
You can't store instance of File within FileReader.
Also the error that you see is because you have not imported java.io.File, so you need to import File like:
import java.io.File;
A side note: You will need to handle FileNotFoundException.
Try importing java.io.File, and change your FileReader line to the following:
FileReader fin = new FileReader(new File("running.txt"));
It compiled fine for me.
Use the following code:
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
import java.io.File;
public class running{
public static void main(String args[]) throws IOException {
double sum=0.0;
double num=0.0;
FileReader fin = (new File("running.txt");
Scanner src = new Scanner(fin);
try{
while (src.hasNext()){
if(src.hasNextDouble()){
num=src.nextDouble();
sum=sum+num;
System.out.println(sum);
}else{
break;
}
}
}catch(Exception e){}finally{fin.close();}
}
}
Im trying to a specific String of number in a csv file and I keep getting an a FileNotFound exception even though the files exists. I cant seem to fix the problem
Sample Csv file
12141895, LM051
12148963, Lm402
12418954, Lm876
User Input : 12141895
Desired Result : True
import javax.swing.*;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;
import javax.swing.*;
import java.io.*;
import java.awt.*;
import java.awt.List;
public class tester
{
public static void main (String [] args ) throws IOException
{
boolean cool = checkValidID();
System.out.println(cool);
}
public static boolean checkValidID() throws IOException
{
boolean results = false;
Scanner scan = new Scanner(new File("C:\\Users\\Packard Bell\\Desktop\\ProjectOOD\\IDandCourse.csv"));
String s;
int indexfound=-1;
String words[] = new String[500];
String word = JOptionPane.showInputDialog("Enter your student ID");
while (scan.hasNextLine())
{
s = scan.nextLine();
if(s.indexOf(word)>-1)
indexfound++;
}
if (indexfound>-1)
{
results = true;
}
else
{
results = true;
}
return results;
}
}
use:
import java.io.File;
import java.io.FileNotFoundException;
Also, in your function declaration try using
public static boolean checkValidID() throws FileNotFoundException
and likewise with the main function.
If the file is present and named correctly, this should handle it.