I'm doing a phonebook and I'd like to save contacts to vcard. I found vcard format on the internet, but I do not know how to read datas from stdin.
package homework;
import java.io.*;
public class SaveToVcard {
public static void vcard() throws IOException {
File file = new File("contact.vcf");
FileOutputStream fop = new FileOutputStream(file);
if (file.exists()) {
String vcard = "BEGIN:VCARD\n" + "VERSION:4.0\n" + "N:Gump;Forrest;;;\n" + "FN:Forrest Gump\n"
+ "ORG:Bubba Gump Shrimp Co.\n" + "TITLE:Shrimp Man\n"
+ "TEL;TYPE=work,voice;VALUE=uri:tel:+1-111-555-1212\n"
+ "TEL;TYPE=home,voice;VALUE=uri:tel:+1-404-555-1212\n" + "EMAIL:forrestgump#example.com\n"
+ "REV:20080424T195243Z\n" + "END:VCARD";
fop.write(vcard.getBytes());
BufferedReader br = null;
String currentLine;
br = new BufferedReader(new FileReader("contact.vcf"));
while ((currentLine = br.readLine()) != null) {
System.out.println(currentLine);
}
fop.flush();
fop.close();
System.out.println("Kész");
} else
System.out.println("A fájl nem létezik");
}
You can use Scanner and do something like this
Scanner sc = new Scanner(System.in);
String input = sc.next();
See https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html
Or maybe you can pass what you need as parameters when running your application
See https://docs.oracle.com/javase/tutorial/essential/environment/cmdLineArgs.html
Related
Sorry If I have any errors because this is my first time asking a question. So basically, my program is converting white_space to underscore and I made it to work. But the problem is, I can't seem to output the inside of my outputfile.txt in the last part of my program.
There should be a premade inputfile.txt for it to work.
Full code:
https://pastebin.com/ecGGd1Z5
Here's the code I'm that's getting problem,
//READING2 No output :(
FileReader yo = new FileReader ("outputfile.txt");
int a;
System.out.println("Outputing from outputfile.txt file ...");
while((a=yo.read())!=-1)
{
System.out.print((char)a);
}
System.out.println("\n");
yo.close();
//
You are not handling the resources correctly. Please find a working example bellow.
It uses "try with resource" so the resource e.g. a FileWriter will be closed correctly:
public class Working {
public static void main(String[] args) throws FileNotFoundException, IOException {
String str;
Scanner scan = new Scanner(System.in);
System.out.println("[Enter source file name: ]");
String input = scan.nextLine();
try (FileReader fread = new FileReader(input)) {
BufferedReader bread = new BufferedReader(fread);
try (FileWriter fwrite = new FileWriter("outputfile.txt")) {
System.out.println(" ");
System.out.println("Creating output file ...");
System.out.println("Output file successly created!");
System.out.println("[Output file name is outputfile.txt]");
System.out.println("=====================");
//READING
FileReader fr = new FileReader(input);
int i;
System.out.println("Outputing from " + input + " file ...");
while ((i = fr.read()) != -1) {
System.out.print((char) i);
}
System.out.println("\n");
fr.close();
//
System.out.println("===========");
System.out.println("Starting to convert spaces to underscore ...");
System.out.println("Success!");
System.out.println("===========");
//
while ((str = bread.readLine()) != null) {
str = str.trim();
str = str.replaceAll(" ", "_");
fwrite.write(str);
}
}
//
//READING2 No output :(
try (FileReader yo = new FileReader("outputfile.txt")) {
int a;
System.out.println("Outputing from outputfile.txt file ...");
while ((a = yo.read()) != -1) {
System.out.print((char) a);
}
System.out.println("\n");
}
}
}
}
From read the line needed to be deleted by the user to delete it
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class Delete {
public static void main(String[] args) throws IOException {
File input = new File("data.txt");
FileReader fr = null;
Scanner ob = new Scanner(System.in);
// declare variable
String DeleteWord, str, newDeleteWord;
System.out.print("Enter word you want to delete: ");
DeleteWord = ob.nextLine();
newDeleteWord = (capitalize(DeleteWord));
try {
fr = new FileReader(input);
BufferedReader br = new BufferedReader(fr);
while ((str = br.readLine()) != null) {
if (str.contains(newDeleteWord)) {
System.out.println(str);
}
Scanner read = new Scanner(System.in);
int selection;
System.out.println("Confirm to delete his/her data?\n 1 for yes\n 2 for no");
selection = read.nextInt();
if (selection == 1)
if (str.contains(newDeleteWord)) {
str = "";
}
}
} finally {
fr.close();
}
}
public static String capitalize(String str1) {
if (str1 == null || str1.isEmpty()) {
return str1;
}
return str1.substring(0, 1).toUpperCase() + str1.substring(1);
}
}
How can I delete lines of data in textfile using java? eg. my textfile is data.txt
This is a possible solution:
File inputFile = new File("myFile.txt"); // File which we will read
File tempFile = new File("myTempFile.txt"); // The temporary file where we will write
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String lineToRemove = yourString; // here is your line to remove
String currentLine;
while((currentLine = reader.readLine()) != null) {
String trimmedLine = currentLine.trim(); // we trim it and remove unecessary spaces
if(trimmedLine.equals(lineToRemove)) continue; // If it is equal to our line to remove then do not write it to our file!
writer.write(currentLine + System.getProperty("line.separator"));
}
writer.close();
reader.close();
inputFile.delete(); // we delete the file that we have so that we have no conflicts
boolean successful = tempFile.renameTo(inputFile);
OR
Reading all the lines in a list and filtering this list.
The quickest way is through Apache Commons-IO ( or you can implement it yourself)
Apache Commons:
List<String> lines = FileUtils.readLines(file);
List<String> updatedLines = lines.stream().filter(s -> !s.contains(searchString)).collect(Collectors.toList());
FileUtils.writeLines(file, updatedLines, false);
This is my following .txt file
.txt file
I want to retrieve IP address based on URl.I have tried the following code but it got failed.Can i do it using Hashmap. This is my first post.I apologize for my mistakes.
public static void main(String args[]) throws IOException {
FileReader fr = new FileReader("C:/Users/charan/Desktop/Resources/HashCheck.txt");
BufferedReader br = new BufferedReader(fr);
Scanner in = new Scanner(System.in);
System.out.println("enter:");
String output = in.next();
String line;
while((line = br.readLine()) != null){
if (line.contains(output))
{
output = line.split(":")[1].trim();
System.out.println(output);
break;
}
else
System.out.println("UrL not found");
break;
}
in.close();
}}
public static void main(String args[]) throws IOException {
FileReader fr = new FileReader("C:/Users/charan/Desktop/Resources/HashCheck.txt");
BufferedReader br = new BufferedReader(fr);
Scanner in = new Scanner(System.in);
System.out.println("enter:");
String output = in.next();
String line;
String myIp = null; //assign a new variable to put IP into
while ((line = br.readLine()) != null) {
if (line.contains(output)) {
myIp = line.split(":")[1].trim(); //assign IP to the new variable
System.out.println(myIp);
break; //break only if you get the IP. else let it iterate over all the elements.
}
}
in.close();
if (myIp == null) { //if the new variable is still null, IP is not found
System.out.println("UrL not found");
}
}
Hello can someone help me? The point of the homework is to read a file then create another file where it replaces all of the words "is" with "was", i have all this done but I am also not sopposed to replace words that have"is" in them, for example: "this, isthmus".
import java.io.*;
import java.util.*;
public class WordChange {
public static void main(String[]args) throws Exception {
FileReader fr = null;
FileWriter fw = null;
try
{
Scanner keyboard=new Scanner(System.in);
System.out.println("Enter the name of the text file: ");
String fileName=keyboard.nextLine();
File file = new File(fileName);
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = "", oldtext = "";
while((line = reader.readLine()) != null)
{
oldtext += line + "\r\n";
}
reader.close();
String replacedtext=oldtext.replaceAll("is ","was ");
FileWriter writer = new FileWriter("output.txt");
writer.write(replacedtext);
writer.close();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
}
just a guess here but instead of
String replacedtext=oldtext.replaceAll("is ","was ");
would this work
String replacedtext=oldtext.replaceAll(" is "," was ");
Im just guessing let me know if it works
I'm trying to read a text files and insert the data from these text files into a URL;
but i have this error "java.lang.illegalargumentexception contains a path separator file"
this is the read method that im using
>
public String ReadFile (String Path){
String res = null;
try {
String filePath = android.os.Environment.getExternalStorageDirectory().getPath() + "/" + Path;
File file = new File(filePath);
if(file.exists()){
InputStream in = openFileInput(filePath);
if (in != null) {
// prepare the file for reading
InputStreamReader input = new InputStreamReader(in);
BufferedReader buffreader = new BufferedReader(input);
res = "";
String line;
while (( line = buffreader.readLine()) != null) {
res += line;
}
in.close();
}else{
}
}else{
Toast.makeText(getApplicationContext(), "The File" + Path + " not Found" ,Toast.LENGTH_SHORT).show();
}
} catch(Exception e){
Toast.makeText(getApplicationContext(),e.toString() + e.getMessage(),Toast.LENGTH_SHORT).show();
}
return res;
}
> String sendername = ReadFile ("SenderName.txt");
String AccountName = ReadFile ("AccountName.txt");
String AccountPassword = ReadFile ("AccountPassword.txt");
String MsgText = ReadFile ("MsgText.txt");
Thanks,
- Though this error doesn't points there, but still have you given the permission to read External Storage in the Manifest.xml file
Try something like this..
public void readFile(String path){
File f = new File(path);
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
String read = new String();
String temRead = new String();
while((temRead = br.readLine())!=null){
read = read + temRead;
}
}