I desperately need help for file input/output in java - java

I need help about inputting using file (file name is inp2.dat) and outputting using file (file name is out2.dat) in the SAME PROGRAM. Do I use FileInputStream and FileOutputStream in the same class? Please help. Its outputting File Not Found.
import java.io.*;
class MBF
{
static String fileinp="inp2.dat";
public void main()
{
boolean EOF=false;
try
{
FileInputStream fr=new FileInputStream(fileinp);
DataInputStream dr=new DataInputStream(fr);
while(!EOF)
{
try
{
System.out.println("Enter no. of inputs:");
int n=dr.readInt();
int max=0;
for(int a=1;a<=n;a++)
{
System.out.println("Enter:");
int p=dr.readInt();
String str=dr.readLine();
max=max+1;
if(str.charAt(1)==str.charAt(0))
max=max+1;
else
max=max+2;
for(int i=0;i<p-2;i++)
{
char f=str.charAt(i);
char s=str.charAt(i+1);
char t=str.charAt(i+2);
if((f==s)&&(f==t))
max=max+1;
else
if(((f==s)&&(f!=t))||((s==t)&&(f!=t))||((f==t)&&(t!=s)))
max=max+2;
else
max=max+3;
}
max=0;
}
}
catch(EOFException el)
{
System.out.println("end of file");
EOF=true;
}
catch(IOException e)
{
System.err.println(e);
}
}
}
catch(FileNotFoundException e)
{
System.out.println("File not found");
}
}
}

There are a few problems throughout. I've made some changes with comments:
class MBF
{
static String fileinp = "C:\\inp2.dat";
public static void main(String[] args) // main method signature was wrong
{
// this line doesn't need to be outside of main, and you aren't using your fileinp string
Scanner in = new Scanner(new File(fileinp));
// added your writer
BufferedWriter out = new BufferedWriter(new FileWriter("C:\\out2.dat"));
System.out.println("Enter no. of inputs:");
int n = in.readInt();
//in.close(); I don't think you meant to do this here.
int max=0;
for(int a = 1; a <= n; a++)
{
System.out.println("Enter:");
// these were originally dr.read... dr is not a variable in scope here. I think you meant in
int p = in.readInt();
String str = in.readLine();
max=max+1;
if(str.charAt(1)==str.charAt(0))
max=max+1;
else
max=max+2;
for(int i = 0; i < p - 2; i++)
{
char f = str.charAt(i);
char s = str.charAt(i + 1);
char t = str.charAt(i + 2);
if ((f == s) && (f == t))
max=max+1;
else if (((f == s) && (f != t)) || ((s == t) && (f != t)) || ((f == t) && (t != s)))
max=max+2;
else
max=max+3;
}
out.write(max + "\n");
max=0;
}
in.close();
out.close();
}
}
Should do what you want.

Related

How I can convert message bundle properties files to READABLE text in UTF-8 format?

https://github.com/essiembre/eclipse-rbe/issues/83
eclipse-rbe
In Eclipse exist file: messagesBundle_ru_RU.properties
#Generated by ResourceBundle Editor (http://essiembre.github.io/eclipse-rbe/)
#Generated by ResourceBundle Editor (http://eclipse-rbe.sourceforge.net)
#Created by JInto - www.guh-software.de
#Sun Nov 18 17:19:12 EET 2012
ABS = \u0410\u0411\u0421
About = \u041E \u043F\u0440\u043E\u0433\u0440\u0430\u043C\u043C\u0435
Add = \u0414\u043E\u0431\u0430\u0432\u043B\u0435\u043D\u0438\u0435 \u0437\u0430\u043F\u0438\u0441\u0438
Add_Condition = \u0414\u043E\u0431\u0430\u0432\u0438\u0442\u044C \u0443\u0441\u043B\u043E\u0432\u0438\u0435
Additional = \u0414\u043E\u043F\u043E\u043B\u043D\u0438\u0442\u0435\u043B\u044C\u043D\u043E
How I can convert this to READABLE text in UTF-8 format?
This is a properties file, and when it was saved to an OutputStream, any character outside of the ISO-8859-1 character set was replaced with a Unicode escape. The Properties.load(InputStream) method will decode this for you. You can then save the properties to a new file, specifying UTF-8 encoding.
static void transcodeProperties(Path src, Path dst) throws IOException {
Properties properties = new Properties();
try (InputStream fis = Files.newInputStream(src);
BufferedInputStream is = new BufferedInputStream(fis)) {
properties.load(is);
}
try (Writer w = Files.newBufferedWriter(dst, StandardCharsets.UTF_8, StandardOpenOption.CREATE_NEW)) {
properties.store(w, null);
}
}
I created a method of doing what you asked. Keep in mind, I used methods from Apache. I extracted the required methods that way you will not be forced to use that library if you do not want to.
public static void translateFileUnicode(File input, File output) {
LinkedList<String> result = new LinkedList<>();
try {
BufferedReader reader = new BufferedReader(new FileReader(input));
String temp = reader.readLine();
while (temp != null) {
result.add(translate(temp));
temp = reader.readLine();
}
reader.close();
BufferedWriter writer = new BufferedWriter(new FileWriter(output));
for (String str : result) {
writer.write(str + '\n');
}
writer.flush();
writer.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static String translate(final CharSequence input) {
if (input == null) {
return null;
}
try {
final StringWriter writer = new StringWriter(input.length() * 2);
translate(input, writer);
return writer.toString();
} catch (final IOException ioe) {
throw new UncheckedIOException(ioe);
}
}
public static void translate(final CharSequence input, final Writer writer) throws IOException {
Objects.requireNonNull(writer, "writer");
if (input == null) {
return;
}
int pos = 0;
final int len = input.length();
while (pos < len) {
final int consumed = translateUnicode(input, pos, writer);
if (consumed == 0) {
final char c1 = input.charAt(pos);
writer.write(c1);
pos++;
if (Character.isHighSurrogate(c1) && pos < len) {
final char c2 = input.charAt(pos);
if (Character.isLowSurrogate(c2)) {
writer.write(c2);
pos++;
}
}
continue;
}
for (int pt = 0; pt < consumed; pt++) {
pos += Character.charCount(Character.codePointAt(input, pos));
}
}
}
public static int translateUnicode(final CharSequence input, final int index, final Writer out) throws IOException {
if (input.charAt(index) == '\\' && index + 1 < input.length() && input.charAt(index + 1) == 'u') {
int i = 2;
while (index + i < input.length() && input.charAt(index + i) == 'u') {
i++;
}
if (index + i < input.length() && input.charAt(index + i) == '+') {
i++;
}
if (index + i + 4 <= input.length()) {
final CharSequence unicode = input.subSequence(index + i, index + i + 4);
try {
final int value = Integer.parseInt(unicode.toString(), 16);
out.write((char) value);
} catch (final NumberFormatException nfe) {
throw new IllegalArgumentException("Unable to parse unicode value: " + unicode, nfe);
}
return i + 4;
}
throw new IllegalArgumentException("Less than 4 hex digits in unicode value: '" + input.subSequence(index, input.length())
+ "' due to end of CharSequence");
}
return 0;
}
If you wish to translate the unicode characters from one file into another all at once you can use the translateFileUnicode(File, File) method. If you wish to translate a single String you can use the translate(CharSequence) method. I hope this is what you were looking for.

Counting number of words start with UpperCase letter in strings, java

I have tried to write a Java program that count number of words start with UpperCase in each line separately, like in a txt file, and print the line number next to the number of words start with UpperCase in that line.
I have only come out with how to count the number for a single line using:
Scanner in = new Scanner(System.in);
String s = new String();
System.out.println("Enter a line:");
s = " " + in .nextLine();
char ch;
int count = 0;
for (int i = 1; i < s.length(); i++) {
ch = s.charAt(i);
if (Character.isUpperCase(ch) && (i == 0 || Character.isWhitespace(s.charAt(i - 1)))) {
count++;
}
}
System.out.println("total number of words start with capital letters are :" + count);
I tried to do it on the way I want, but it keep showing me "File is empty":
FileInputStream in = new FileInputStream("io-02.txt");
Scanner inScanner = new Scanner(in);
FileOutputStream out = new FileOutputStream("io-02-out.txt");
PrintWriter pwr = new PrintWriter(out);
int linenumb=0;
String s="";
char c;
int count = 0;
inScanner.useDelimiter("");
for (int i = 1; i < s.length(); i++) {
s = " " + inScanner.nextLine().trim();
c = s.charAt(i);
if (Character.isUpperCase(c) && (i == 0 || Character.isWhitespace(s.charAt(i - 1)))) {
count++;
} else if(s == "\n"){
if(linenumb == 0)
pwr.printf("%6s%35s%n", "Line#", "Number of Uppercase characters");
linenumb++;
pwr.printf("%5d.%35d%n", linenumb, count);
count = 0;
}
}
if(linenumb == 0)
System.out.println("Error: The input file is empty");
else{
linenumb++;
pwr.printf("%5d.%35d%n", linenumb, count);
System.out.println("The file output.txt has been created . . . ");
}
Please help.
Java 8 solution:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
final public class UppercaseWordCounter { // https://stackoverflow.com/questions/49193228/counting-number-of-words-start-with-uppercase-letter-in-strings-java
final private static File FILE_WORDS = new File("io-02.txt");
final private static File FILE_RESULTS = new File("io-02-out.txt");
public static void main(final String[] args) {
if (!FILE_WORDS.exists()) {
System.err.println("Input file does not exist: " + FILE_WORDS);
System.exit(1);
}
if (FILE_RESULTS.exists()) {
if (!FILE_RESULTS.delete()) {
System.err.println("Intended output file exists already and can't be deleted: " + FILE_RESULTS);
System.exit(2);
}
}
try (final BufferedReader br = Files.newBufferedReader(FILE_WORDS.toPath(), StandardCharsets.UTF_8);
final BufferedWriter bw = Files.newBufferedWriter(FILE_RESULTS.toPath(), StandardCharsets.UTF_8)) {
int lineCounter = 1;
String line;
while ((line = br.readLine()) != null) {
final int upperCaseWordsInThisLine = countUpperCaseWords(line);
bw.write("Line " + lineCounter + " has " + upperCaseWordsInThisLine + " upper case word" + (upperCaseWordsInThisLine == 1 ? "" : "s") + ".\n");
lineCounter++;
}
} catch (Exception e) {
e.printStackTrace();
}
System.exit(0);
}
private static int countUpperCaseWords(final String line) {
int ret = 0;
final int length = line.length();
boolean newWord = true;
for (int i = 0; i < length; i++) {
final char c = line.charAt(i);
if (" .,;/".indexOf(c) >= 0) {
newWord = true;
} else if (newWord) {
newWord = false;
if (Character.isUpperCase(c)) {
ret++;
}
}
}
return ret;
}
}
Why don't you use a method from Files class, which is available from java 1.7
List<String> lst = Files.readAllLines(Path path, Charset cs)
then you can loop over the lst List checking your condition

Error: ; expected (Compile error in Java)

When isLetter() method is deleted everything is working fine but when I add it it gives an error. I removed private as it is in the main method. Please help. Thanks in advance.
import java.io.*;
class WordCounter{
public static void main(String args[]){
File file_in_obj = new File("E:/Problems","notes.txt");
File file_out_obj = new File("E:/Problems","notes_sorted.txt");
boolean isLetter(char let){
return ( let>= 'a'&& let <= 'z') || ( let >= 'A' && let <='Z');
}
try(BufferedReader fin = new BufferedReader(new FileReader(file_in_obj));
BufferedWriter fout = new BufferedWriter(new FileWriter(file_out_obj));){
String array[]=new String[500];
char ch[]=new char[25];
int rd,k=0;
String line=null;
/*do{
rd=fin.read();
if(Character.isWhitespace((char)rd))
fout.write(" ");
else if(Character.isLetter((char)rd)){
fout.write((char)rd);
}
}while(rd!=-1); */
while((line=fin.readLine())!=null){
// System.out.println(j++);
String[] tokens = line.split ("\\s+");
for(int i = 0; i < tokens.length; i++){
array[k]=tokens[i];
fout.write(array[k]+" ");
k++;
//System.out.println(tokens.length);
}
}
for(int p=0;p<k;p++){
for(int i=0;i<array[p].length();i++){
if(Character.isLetter(array[p].charAt(i)))
System.out.print(array[p].charAt(i));
}
System.out.println(p);
}
/*for(int j=tokens.length;j>1;j--)
for(int i=0;i<j-1;i++){
if(tokens[i].compareTo(tokens[i+1])>0){
String temp=tokens[i+1];
tokens[i+1]=tokens[i];
tokens[i]=temp;
}
}*/
} catch(IOException e){
System.out.println("I/O Exception occured");
}
}
}
You can't have a method inside another method. Try this:
boolean isLetter(char let){
return ( let>= 'a'&& let <= 'z') || ( let >= 'A' && let <='Z');
}
public static void main(String args[]){
File file_in_obj = new File("E:/Problems","notes.txt");
File file_out_obj = new File("E:/Problems","notes_sorted.txt");
...
}

Java - Writing a Method to Count Lines In a Text File Without Throwing Exceptions

Below is a solution from Number of lines in a file in Java
to quickly count the number of lines in a text file.
However, I am trying to write a method that will perform the same task without throwing an 'IOException'.
Under the original solution is my attempt to do this with a nested try-catch block <-- (Is this usually done/frowned upon/ or easily avoidable??) which returns 0 no matter how many lines are in the given file (obviously a fail).
Just to be clear, I am not looking for advice on how to better use the original method that does contain the exception and, therefore, the context within which I am using it is irrelevant to this question.
Can somebody please help me write a method that counts the number of lines in a text file and does not throw any exceptions? (In other words, deals with potential errors with a try-catch.)
Original line counter by martinus:
public static int countLines(String filename) throws IOException {
InputStream is = new BufferedInputStream(new FileInputStream(filename));
try {
byte[] c = new byte[1024];
int count = 0;
int readChars = 0;
boolean empty = true;
while ((readChars = is.read(c)) != -1) {
empty = false;
for (int i = 0; i < readChars; ++i) {
if (c[i] == '\n') {
++count;
}
}
}
return (count == 0 && !empty) ? 1 : count;
} finally {
is.close();
}
}
My Attempt:
public int countLines(String fileName ) {
InputStream input = null;
try{
try{
input = new BufferedInputStream(new FileInputStream(fileName));
byte[] count = new byte[1024];
int lines = 0;
int forChar;
boolean empty = true;
while((forChar = input.read(count)) != -1){
empty = false;
for(int x = 0; x < forChar; x++){
if(count[x] == '\n'){
lines++;
}
}
}
return (!empty && lines == 0) ? 1 : lines + 1;
}
finally{
if(input != null)
input.close();
}
}
catch(IOException f){
int lines = 0;
return lines;
}
}
It is more robust to use char instead of byte for '\n' and return -1 in case of any errors, for example if the filename does not exist:
public static int countLines(String filename) {
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(new FileInputStream(filename)));
char[] c = new char[1024];
int count = 0;
int readChars = 0;
boolean emptyLine = true;
while ((readChars = br.read(c)) != -1) {
for (int i = 0; i < readChars; ++i) {
emptyLine = false;
if (c[i] == '\n') {
++count;
emptyLine = true;
}
}
}
return count + (!emptyLine ? 1 : 0);
} catch (IOException ex) {
return -1;
} finally {
if (br != null)
try {
br.close();
} catch (IOException e) {
// Ignore intentionally
}
}
}
Sharing my attempt.
public static int countLines(String filename) {
InputStream is = new BufferedInputStream(new FileInputStream(filename));
int numLines = 0;
try {
byte[] c = new byte[1024];
int count = 0;
int readChars = 0;
boolean empty = true;
while ((readChars = is.read(c)) != -1) {
empty = false;
for (int i = 0; i < readChars; ++i) {
if (c[i] == '\n') {
++count;
}
}
}
numLines = (count == 0 && !empty) ? 1 : count;
} catch (IOException ex) {
numLines = 0;
} catch (FileNotFoundException ex) {
System.out.println("File not found.");
numLines = 0;
} finally {
is.close();
}
return numLines;
}

"Cannot Find Symbol - method hasNextLine()" error in Java

I am trying to write a program that uses file I/O to score personality tests. However, when I get to this code:
while (f.hasNextLine()) {
I get the error described in the title. Here is the code in its entirety. I import all of the necessary I/O and utilities prior and I think I am declaring the file variable correctly. I know that this method exists, but what is the problem?
import java.io.*;
import java.util.*;
public class PersonalityTest {
public static Scanner input = new Scanner(System.in);
public static void main(String[] args) throws IOException {
String input = input();
String output = output();
results(input, output);
System.out.println("Your results are located in the file you requested.");
}
public static String input() throws IOException {
System.out.print("Input file name: ");
String file = input.nextLine();
File f = new File(file);
System.out.println();
while (!f.exists()) {
System.out.print("File not found. Try again: ");
file = input.nextLine();
f = new File(file);
System.out.println();
}
return file;
}
public static String output() {
System.out.print("Output file name: ");
String output = input.nextLine();
return output;
}
public static void results(String input, String output) throws IOException {
PrintStream write = new PrintStream(new File(output));
File f = new File(input);
while (f.hasNextLine()) {
String name = f.nextLine();
String type = "ESTJ";
String answers = f.nextLine();
char[] choices = new char[70];
for (int i = 0; i <= 69; i++) {
choices[i] = answers.charAt(i);
}
int aCount = 0;
int bCount = 0;
for (int i = 0; i <= 69; i+=7) {
if (choices[i].toLowerCase == 'a') {
aCount+=1;
}
if (choices[i].toLowerCase == 'b') {
bCount+=1;
}
}
int pct1 = (int)Math.round((bCount/(aCount+bCount))*100);
if (pct1 > 50) {
type.replace('E','I');
}
if (pct1 == 50) {
type.replace('E','X');
}
int aCount2 = 0;
int bCount2 = 0;
for (int i = 2; i <= 69; i+=7) {
if (choices[i].toLowerCase == 'a') {
aCount2+=1;
}
if (choices[i].toLowerCase == 'b') {
bCount2+=1;
}
if (choices[i+1].toLowerCase == 'a') {
aCount2+=1;
}
if (choices[i+1].toLowerCase == 'b') {
bCount2+=1;
}
}
int pct2 = (int)Math.round((bCount2/(aCount2+bCount2))*100);
if (pct2 > 50) {
type.replace('S','N');
}
if (pct2 == 50) {
type.replace('S','X');
}
int aCount3 = 0;
int bCount3 = 0;
for (int i = 4; i <= 69; i+=7) {
if (choices[i].toLowerCase == 'a') {
aCount3+=1;
}
if (choices[i].toLowerCase == 'b') {
bCount3+=1;
}
if (choices[i+1].toLowerCase == 'a') {
aCount3+=1;
}
if (choices[i+1].toLowerCase == 'b') {
bCount3+=1;
}
}
int pct3 = (int)Math.round((bCount3/(aCount3+bCount3))*100);
if (pct3 > 50) {
type.replace('T','F');
}
if (pct3 == 50) {
type.replace('T','X');
}
int aCount4 = 0;
int bCount4 = 0;
for (int i = 6; i <= 69; i+=7) {
if (choices[i].toLowerCase == 'a') {
aCount4+=1;
}
if (choices[i].toLowerCase == 'b') {
bCount4+=1;
}
if (choices[i+1].toLowerCase == 'a') {
aCount4+=1;
}
if (choices[i+1].toLowerCase == 'b') {
bCount4+=1;
}
}
int pct4 = (int)Math.round((bCount4/(aCount4+bCount4))*100);
if (pct4 > 50) {
type.replace('J','P');
}
if (pct4 == 50) {
type.replace('J','X');
}
write.println(name + ": [" + pct1 + ", " + pct2 + ", " + pct3 + ", " + pct4 + "] = " + type);
write.close();
}
}
}
java.io.File does not have a hasNextLine() method. That's a method that exists in java.util.Scanner. Scanner has a constructor that takes a File object as an argument and allows it to use the specified file for input - you should probably try using that one:
Scanner s = new Scanner(new File(input));
EDIT:
That said, Scanner can be a bit of a performance killer (a bit?). It is often faster to use a BufferedReader and its readLine() method to read a single line into a String object and then parse the String manually. You can get a BufferedReader from a File with a bit of trickery:
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
instead of using hasNextLine() method, which is non-existent in a File object, an alternative would be to access your file using an inputstream class like FileInputStream and wrapped inside a decorator class like BufferedReader, which would allow you to read its contents per line, using readLine() method....

Categories

Resources