I am trying to do the following: I am making a program in Java which let me create and read text files. So far I have been able to do this, but the hard(?) part is this: I have to be able to get an error when anything else but A, B or C is inside the text file.
So far I got:
package textfile;
import java.io.*;
import static java.lang.System.*;
class OutWrite {
public static void main(String[] args) {
try{
FileWriter fw = new FileWriter("FAS.txt");
PrintWriter pw = new PrintWriter(fw);
pw.println("A");
pw.println("B");
pw.println("C");
pw.close();
} catch (IOException e){
out.println("ERROR!");
}
}
}
And
package textfile;
import java.io.*;
import static java.lang.System.*;
class InRead {
public static void main(String[] args) {
try {
FileReader fr = new FileReader("FSA.txt");
BufferedReader br = new BufferedReader(fr);
String str;
while ((str = br.readLine()) != null){
out.println(str);
}
br.close();
} catch (IOException e) {
out.println("File not found");
}
}
}
Can anyone steer me in the right direction, please?
Just throw Exception when a new Character is found other than A,B,C .
use,
class InRead {
public static void main(String[] args) {
try {
FileReader fr = new FileReader("FSA.txt");
BufferedReader br = new BufferedReader(fr);
String str;
while ((str = br.readLine()) != null) {
if (str.equals("A") || str.equals("B") || str.equals("c")) //compare
out.println(str);
else
throw new Exception(); //throw exception
}
br.close();
} catch (IOException e) {
out.println("File not found");
}
catch (Exception e) {//catch it here and print the req message
System.out.println("New Character Found");
}
}
}
Related
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class hello {
public static void main(String[] args) {
try {
FileReader fin = new FileReader("c:\\windows\\system.ini");
Scanner scn = new Scanner(fin);
while (scn.hasNext()) {
String tmp = scn.nextLine();
System.out.println(tmp);
}
fin.close();
scn.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
how can i print c:\windows\system.ini (path? file?name).
Is there any way to print the path?
Check this out:
try {
File file = new File("c:\\windows\\system.ini");
FileReader fileReader = new FileReader(file);
System.out.println(file.getName());
System.out.println(file.getPath());
Scanner scn = new Scanner(fileReader);
while (scn.hasNext()) {
String tmp = scn.nextLine();
System.out.println(tmp);
}
fileReader.close();
scn.close();
}catch (Exception e) {
}
you can use File then pass it to FileReader.
import java.io.*;
import java.util.Random;
import java.util.Scanner;
class EncryptDecryptFile{
public String readEncryptionFile()
{
String contentLine1 = "";
//String encryptFilename = Solution.filepath + "EncryptionFile.txt";
BufferedReader br = null;
try
{
br = new BufferedReader(new FileReader("C:\\Users\\HP\\Desktop\\EncryptionFile.txt"));
String contentLine = br.readLine();
while (contentLine != null)
{
contentLine1 = contentLine;
}
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
finally
{
try
{
if(br != null)
br.close();
}
catch (IOException ioe)
{
System.out.println("Error in closing the BufferedReader");
}
}
return contentLine1;
}
public void writeDecryptionFile(String message)
{
BufferedWriter bw = null;
//String decryptFilename = Solution.filepath + "DecryptionFile.txt";
try
{
File file = new File("C:\\Users\\HP\\Desktop\\DecryptionFile.txt");
if (!file.exists())
{
file.createNewFile();
FileWriter fw = new FileWriter(file);
bw = new BufferedWriter(fw);
bw.write(message);
}
else
{
FileWriter fw = new FileWriter(file);
bw = new BufferedWriter(fw);
bw.write(message);
}
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
finally
{
try
{
if(bw!=null)
bw.close();
}
catch(Exception ex)
{
System.out.println("Error in closing the BufferedWriter"+ex);
}
}
}
}
public class Solution {
public static String filepath = "C:\\Users\\HP\\Desktop\\";
private static String generateString()
{
char[] chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890".toCharArray();
StringBuilder generatedString = new StringBuilder(20);
Random random = new Random();
for (int i = 0; i < 40; i++) {
char c = chars[random.nextInt(chars.length)];
generatedString.append(c);
}
return generatedString.toString();
}
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
String message = sc.nextLine();
try{
EncryptDecryptFile f = new EncryptDecryptFile ();
String encryptFilename = Solution.filepath + "EncryptionFile.txt";
String generatedString = generateString();
BufferedWriter writer = new BufferedWriter(new FileWriter("C:\\Users\\HP\\Desktop\\EncryptionFile.txt"));
writer.write(generatedString);
writer.close();
if(f.readEncryptionFile().equals(generatedString))
{
f.writeDecryptionFile(message);
String decryptFilename = Solution.filepath + "DecryptionFile.txt";
BufferedReader reader = new BufferedReader(new FileReader("C:\\Users\\HP\\Desktop\\DecryptionFile.txt"));
String messageFromFile = reader.readLine();
reader.close();
System.out.println(messageFromFile);
}
}
catch (Exception ex)
{
System.out.println(ex.getMessage());
}
}
}
When I write in the Decryption.txt file using writeDecryptionFile(message) method the file not accept the message.
There are two method readEncryptionFile() method and writeDecryptionFile(message) method.
readEncryptionFile() read the content from Encryption.txt and it matches with generatedString if it equals true then,
writeDecryptionFile(message) method write the message String message = sc.nextLine(); to the Decryption.txt file.
instead of this you can use library to decrypt and encrypt.
I'm not quite sure, what you are trying to ask, but it seem's like you are missing a 'flush' in writeDecryptionFile
...
bw = new BufferedWriter(fw);
bw.write(message);
bw.flush();
...
without the flush the buffered characters are never written to the stream
https://docs.oracle.com/javase/7/docs/api/java/io/BufferedWriter.html#flush()
I have a Java program that troubleshoots common problems with phones. To do this I have set up a scanner that reads the user input for any keywords. If one of these keywords is found, a method will output from a text file a solution to the problem suggested by that keyword.
My problem is that when I run the program, all the lines from the text file are outputted, from every method, disregarding my input.
Here's the code:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class task2 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("What is your problem?");
String input = scan.nextLine();
String[] problems = {"screen", "display", "broken", "cracked", "camera", "flash", "ports"};
String[] solutions = input.split("broken");
for(int x=0; x < problems.length; x++){
if(input.contains("broken")){
if(input.contains("screen")){
brokenScreen();
} else{
}
if(input.contains("display")) {
brokenDisplay();
} else{
}
if(input.contains("camera")) {
brokenCamera();
} else{
}
if(input.contains("flash")) {
brokenFlash();
} else{
}
if(input.contains("ports")) {
brokenPorts();
} else{
}
}
else{
}
if(input.contains("cracked")) {
if(input.contains("screen")) {
crackedScreen();
} else{
}
}
if(input.contains("water")) {
waterPhone();
}
else{
}
}
brokenScreen();
brokenDisplay();
crackedScreen();
brokenCamera();
brokenFlash();
brokenPorts();
waterPhone();
noSolution();
}
public static void noSolution() {
String file = "C:/Users/Nicholas Gawley/workspace/Second Practice Controlled Assessment/src/solutions.txt"; //Location of the text file
try {
FileReader filereader = new FileReader(file);
BufferedReader bufferedreader = new BufferedReader(filereader);
while((file = bufferedreader.readLine()) != null){
System.out.println(file);
}
bufferedreader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void waterPhone() {
String file = "C:/Users/Nicholas Gawley/workspace/Second Practice Controlled Assessment/src/solutions.txt"; try {
FileReader filereader = new FileReader(file);
BufferedReader bufferedreader = new BufferedReader(filereader);
while((file = bufferedreader.readLine()) != null){
System.out.println(file);
}
bufferedreader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void brokenPorts() {
String file = "C:/Users/Nicholas Gawley/workspace/Second Practice Controlled Assessment/src/solutions.txt"; try {
FileReader filereader = new FileReader(file);
BufferedReader bufferedreader = new BufferedReader(filereader);
while((file = bufferedreader.readLine()) != null){
System.out.println(file);
}
bufferedreader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void brokenFlash() {
String file = "C:/Users/Nicholas Gawley/workspace/Second Practice Controlled Assessment/src/solutions.txt"; try {
FileReader filereader = new FileReader(file);
BufferedReader bufferedreader = new BufferedReader(filereader);
while((file = bufferedreader.readLine()) != null){
System.out.println(file);
}
bufferedreader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void brokenCamera() {
String file = "C:/Users/Nicholas Gawley/workspace/Second Practice Controlled Assessment/src/solutions.txt"; try {
FileReader filereader = new FileReader(file);
BufferedReader bufferedreader = new BufferedReader(filereader);
while((file = bufferedreader.readLine()) != null){
System.out.println(file);
}
bufferedreader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void crackedScreen() {
String file = "C:/Users/Nicholas Gawley/workspace/Second Practice Controlled Assessment/src/solutions.txt"; try {
FileReader filereader = new FileReader(file);
BufferedReader bufferedreader = new BufferedReader(filereader);
while((file = bufferedreader.readLine()) != null){
System.out.println(file);
}
bufferedreader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void brokenDisplay() {
String file = "C:/Users/Nicholas Gawley/workspace/Second Practice Controlled Assessment/src/solutions.txt"; try {
FileReader filereader = new FileReader(file);
BufferedReader bufferedreader = new BufferedReader(filereader);
while((file = bufferedreader.readLine()) != null){
System.out.println(file);
}
bufferedreader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void brokenScreen() {
String file = "C:/Users/Nicholas Gawley/workspace/Second Practice Controlled Assessment/src/solutions.txt"; try {
FileReader filereader = new FileReader(file);
BufferedReader bufferedreader = new BufferedReader(filereader);
while((file = bufferedreader.readLine()) != null){
System.out.println(file);
}
bufferedreader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Can anyone please solve this issue? Any help would be greatly appreciated.
Remove
brokenScreen();
brokenDisplay();
crackedScreen();
brokenCamera();
brokenFlash();
brokenPorts();
waterPhone();
noSolution();
at the end of your main method (after the for loop).
How can I read a file into a array of String[] and then convert it into ArrayList?
I can't use an ArrayList right away because my type of list is not applicable for the arguments (String).
So my prof told me to put it into an array of String, then convert it.
I am stumped and cannot figure it out for the life of me as I am still very new to java.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* Created by tsenyurt on 06/04/15.
*/
public class ReadFile
{
public static void main(String[] args) {
List<String> strings = new ArrayList<>();
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("/Users/tsenyurt/Development/Projects/java/test/pom.xml"));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
strings.add(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
there is a code that reads a file and create a ArrayList from it
http://www.mkyong.com/java/how-to-read-file-from-java-bufferedreader-example/
Well there are many ways to do that,
you can use this code if you want have a List of each word exist in your file
public static void main(String[] args) {
BufferedReader br = null;
StringBuffer sb = new StringBuffer();
List<String> list = new ArrayList<>();
try {
String sCurrentLine;
br = new BufferedReader(new FileReader(
"Your file path"));
while ((sCurrentLine = br.readLine()) != null) {
sb.append(sCurrentLine);
}
String[] words = sb.toString().split("\\s");
list = Arrays.asList(words);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)
br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
for (String string : list) {
System.out.println(string);
}
}
public static void main(String[] args) throws IOException {
String filename = "C:\\audiofile.wav";
InputStream in = null;
try{
in = new FileInputStream(filename);
}
catch(FileNotFoundException ex){
System.out.println("File not found");
}
AudioStream s = null;
s = new AudioStream(in);
AudioPlayer.player.start(s);
}
i have written this code in netbeans. Name of my audio file is audiofile.wav. But it is all time showing the exception "file not found". Can anyone help me ???
root folders in C drive of Windows Vista and above are protected by UAC. This requires you to run the java executable in Administrative mode.
However, you can shift the wav file elsewhere, where UAC will not interfere(like Documents folder of your currently logged in user) or the root of a different drive(Eg. D:\ and E:)
Also, make sure that the audiofile.wav is indeed in the said location(C:\audiofile.wav)
I think first, you should paste your exception code!
then, I think java I/O support the both two way:
"C:/audiofile.wav"
"C:\audiofile.wav"
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) {
// write your code here
String fileLocation = "C:\\1.diff";
String fileLocation1 = "C:/1.diff";
try {
FileInputStream f = new FileInputStream(fileLocation);
BufferedReader reader = new BufferedReader(new InputStreamReader(f));
String line = reader.readLine();
System.out.println("11111111111111111111111111");
while (line != null) {
// Process line
line = reader.readLine();
System.out.println(line);
}
System.out.println("11111111111111111111111111");
} catch (Exception ex) {
System.out.println(ex);
}
try {
FileInputStream ff = new FileInputStream(fileLocation1);
BufferedReader reader1 = new BufferedReader(new InputStreamReader(ff));
String line1 = reader1.readLine();
System.out.println("2222222222222222222222222");
while (line1 != null) {
// Process line
line1 = reader1.readLine();
System.out.println(line1);
}
System.out.println("2222222222222222222222222");
} catch (Exception ex) {
System.out.println(ex);
}
}
}
it works. I don't know what you did, anyway paste your error msg!
====
```
private static void B() {
String filename = "C:\\test.wav";
InputStream in = null;
try {
in = new FileInputStream(filename);
} catch (FileNotFoundException ex) {
System.out.println("File not found");
}
try {
AudioStream s = new AudioStream(in);
AudioPlayer.player.start(s);
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
```
it works!
Try just placing your file in a different location and see what happens
ProjectRootDir
audiofile.wav
src
And running this String
String filename = "audiofile.wav";