gpt4 book ai didi

java - 如何使用 NetBeans 在 Java 程序中包含文本文件

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:16:13 26 4
gpt4 key购买 nike

我想在我的 Java 程序中包含一个 test.txt 文件,但我不知道如何在 Java 应用程序的 NetBeans 中包含一个文件。

这是我的代码:

package project;
import java.util.*;
import java.io.*;
import java.io.IOException;

public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws IOException
{
new Main().run();
}

public void run()
{
System.out.println("Input String:\n");////
Scanner keyboardScanner = new Scanner(System.in);/////
String inString = keyboardScanner.nextLine();/////
String shortMessage = shortifyMessage(inString);
System.out.println(shortMessage);
}

public String shortifyMessage(String str)
{
String s = str;
String tok1, tok2;
try{
FileInputStream fstream = new FileInputStream("textfile.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
String file_name = "C:/textfile.txt";
try {
textfile file = new textfile(file_name);
String[] aryLines = file.OpenFile();
int i;
for (i=0; i<aryLines.length; i++){
System.out.println(aryLines[i]);
}
}
catch (IOException e) {
System.err.format("File Does not exist\n");
}
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
StringTokenizer tokenizer=new StringTokenizer(strLine,"=");
tok1=tokenizer.nextToken();
tok2=tokenizer.nextToken();

//System.out.println(tok1 + " = " + tok2);

if(s.indexOf(tok1)>0)
s = s.replaceAll(tok1, tok2);
//System.out.println (s);
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
return s;
}
}

当我运行这段代码时出现错误:

Error: textfile.txt (The system cannot find the file specified)

我不知道如何包含 text.txt 文件,以便我的代码可以读取文件的内容并执行适当的功能。

最佳答案

听起来您正在尝试读取文本文件并对其进行解析。在这种情况下,您可以像这样逐行读取文件:

File file = new File("test.txt");
Scanner in = new Scanner(file);
while (in.hasNextLine())
{
String line = in.nextLine();
System.out.println(line);
}

由于您使用的是 NetBeans,它应该会告诉您需要导入和 try catch 的内容。

请注意,如果这就是您的意思,“包含”对于许多程序员(尤其是具有 C++ 背景的程序员)通常意味着您想从某个地方获取源代码并将其“包含”为您的一部分程序。如果这就是您想要做的,并且您的“test.txt”实际上是 Java 代码,您可以将它放在本地 NetBeans 项目源目录中并给它一个“.java”扩展名。

关于java - 如何使用 NetBeans 在 Java 程序中包含文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6798049/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com